Is it possible to create extension of final
classes like String? Like in swift it is possible to add additional methods inside a extension
of final
class
.
For an example - I would like to create a method in String
extension which will tell me String
have valid length for password.
val password : String = mEdtPassword!!.getText().toString()
// how to define haveValidLength method in extension
val isValid : Boolean = password.haveValidLength()
Note - That example is just for a sake to understand usability of extension
, not a real scenario.
You can do that with extension functions in Kotlin. With extensions, you are able to add extra functionality to a class that you do or do not have access to; for example a legacy code base. In the example given in the Kotlin docs here,
swap
was added toMutableList<Int>
which doesn't haveswap
originally. Athis
keyword is used that refers to the object that the swap functionality will operate on. In the example below,this
refers totestList
Trying to add more detail, this answer might be helpful for someone.
Yes we can add additional methods to
final
classes likeString
. For an example I would like to add one method inString
which will tell me that myString
have valid number of characters for password or not.So what I have to do is, I have ti create a below function which can be written in same
class
or at different separateclass
file.And now from anywhere call
Suggestion
If your application just has a single password validation, then there is no problem.
However, I don't suggest you write such a extension method
hasValidPassword
if the application has more than one validation. since the extension method is satically, you can't change yourhasValidPassword
in runtime. So if you want to change the validation in runtime, you should using a function instead, for example:In other words, the extension method above violates Single Responsibility Principle, it does validation & string operations.
yes, you can. Kotin extension method provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator.
Below is an extension method for a
String
:And the extension method code generated as Java below:
So an extension method in Kotlin is using delegation rather than inheritance.
Then you can calling an extension method like as its member function as below:
You also can write an extension method for the existing extension function, for example:
But you can't write an extension method for the existing member function, for example: