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 }
Kotlin extensions provide the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern such as Decorator. These extensions basically add some functionality in an existing class without extending the class.
Are you using Intellij IDEA or Android Studio? Open a Kotlin file that has extension functions, go to Tools -> Kotlin -> Show bytecode, and from the bytecode window that pops up choose Decompile. You'll see what the Java analog of that code looks like and it'll quickly become apparent what the trick is!
Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.
You can create an extension property with overridden getter and setter:
var A.someProperty: Int get() = /* return something */ set(value) { /* do something */ }
But you cannot create an extension property with a backing field because you cannot add a field to an existing class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With