how i can initialized var in interface?
# android
m
how i can initialized var in interface?
p
Or you can do an extension property like:
Copy code
val MyInterface.prop: Int by lazy { 123 }
y
That's actually not possible ☝️
p
or
Copy code
val MyInterface.prop: Int 
    get() = 123
But it’ll be always fetched but you can do it with an object.
@yoavst Is it not?
y
Where will the delegate object be stored?
p
It creates the value every time, ideally you want to have an object that provides it
If you want to leave it localised you can do this too:
Copy code
interface MyInterface {
    object Prop {
        operator fun getValue(thisRef: Any, property: KProperty<*>): Int = 123
    }
}

val MyInterface.prop: Int by MyInterface.Prop
Also worth to say that it’s a global. If you want to do it for each subclass it’s a bit more complicated (especially if you want a
var
instead of a
val
) You may have to start using a companion cache and such, potentially giving you leaks (unless you use WeakReferences)
y
Your first version with the lazy delegation, does it compile?
p
yeah, beacuse
lazy
is a property delegate so it has the
getValue
operator
v
in many libs we see this default value for fields issue solved by using annotations
without knowing the problem is hard to give a good answer but the closest I see to get what you want is this:
interface MyInterface { var _prop: Int? var prop: Int get() = if (_prop!=null) _prop!! else 1 set(value) { _prop = value } }
y
wow @pablisco , I didn't know that you could use a delegate on extension properties (of course it would have been global, but still). Good to know that for DSL stuff!
p
Yeah! Delegation is equal part amazing and dangerous 😁
K 1