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
Tobias Berger
11/27/2020, 10:29 AM
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.
Tobias Berger
11/27/2020, 10:32 AM
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
t0yger
11/27/2020, 10:35 AM
Oops. I still need to study more. thx!!
t
Tobias Berger
11/27/2020, 10:41 AM
Let me clarify with a real world example:
Your interface/class (here
Test
) defines a ratchet box like this:
Tobias Berger
11/27/2020, 10:41 AM
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
t0yger
11/27/2020, 10:46 AM
I got it. it is a crazy way to break box.
Stop before the box owner gets angry.