Monday 20 November 2017

Extension fields in Kotlin

itemprop="text">

It's easy to write extension methods
in Kotlin:



class A {
}
class B {
fun A.newFunction() { ...
}
}



But
is there some way to create extension variable?
Like:



class B {
var
A.someCounter: Int = 0
}


Answer




No - the href="https://kotlinlang.org/docs/reference/extensions.html"
rel="noreferrer">documentation explains
this:






Extensions do not actually modify classes they extend. By defining an
extension, you do not insert new members into a class, but merely make new functions
callable with the dot-notation on instances of this
class.




and





Note that, since extensions do not actually insert members into classes,
there’s no efficient way for an extension property to have a backing field. This is why
initializers are not allowed for extension properties. Their behavior can only be
defined by explicitly providing
getters/setters.





Thinking
about extension functions/properties as just syntactic sugar for calling a static
function and passing in a value hopefully makes this clear.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...