Extension fields in Kotlin

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
}
Jon Skeet
people
quotationmark

No - the 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.

people

See more on this question at Stackoverflow