https://kotlinlang.org logo
Title
m

morozov

09/01/2017, 4:13 PM
how i can initialized var in interface?
p

pablisco

09/01/2017, 4:25 PM
Or you can do an extension property like:
val MyInterface.prop: Int by lazy { 123 }
y

yoavst

09/01/2017, 4:26 PM
That's actually not possible ☝️
p

pablisco

09/01/2017, 4:27 PM
or
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

yoavst

09/01/2017, 4:29 PM
Where will the delegate object be stored?
p

pablisco

09/01/2017, 4:29 PM
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:
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

yoavst

09/01/2017, 4:45 PM
Your first version with the lazy delegation, does it compile?
p

pablisco

09/01/2017, 5:10 PM
yeah, beacuse
lazy
is a property delegate so it has the
getValue
operator
v

villela

09/01/2017, 6:22 PM
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

yoavst

09/01/2017, 7:12 PM
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

pablisco

09/01/2017, 7:23 PM
Yeah! Delegation is equal part amazing and dangerous 😁
:kotlin: 1