Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension fields in Kotlin

Tags:

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 } 
like image 414
Letfar Avatar asked Apr 08 '16 14:04

Letfar


People also ask

What are extensions in Kotlin?

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.

How do Kotlin extensions work?

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!

What is extension function and why it is used in Kotlin?

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.


1 Answers

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.

like image 66
Michael Avatar answered Sep 21 '22 03:09

Michael