Hi! I want to define an extension variable. Howev...
# announcements
t
Hi! I want to define an extension variable. However, as you all know, I don’t have a field because I can’t initialize it. How do you implement it?
Copy code
interface Test {
    val a: String
}

var Test.b: String
    get() = field
    set(value) = field = value
t
Well, basically you don't. Extensions don't modify the class, in Java terms they are just static methods (event if you define a property). Objects of your receiver class have do not "contain" extension properties. In theory you could do something like this:
Copy code
private val bValues = mutableMapOf<Test, String>()
var Test.b: String?
    get() = bValues[this]
    set(value) { bValues[this] = value }
but that has MEMORY LEAK written all over it, because the map will keep the Test instances in memory, even if you don't need them anywhere else.
The reason you don't have a field is not that you can't initialize it. You just don't have anywhere to put it.
t
Oops. I still need to study more. thx!!
t
Let me clarify with a real world example: Your interface/class (here
Test
) defines a ratchet box like this:
Now you're trying to create an extension property
hammer
that allows you to pull a hammer from that box or put it in. But there is no space for it in the actual box, because it wasn't designed to contain a hammer.
t
I got it. it is a crazy way to break box. Stop before the box owner gets angry.