https://kotlinlang.org logo
Title
r

robin

02/16/2017, 1:55 PM
@miha-x64 Oh I see what you're getting at, if you just want to use the views you can do so without the lazy, yes. But if you add them as properties to your activity, e.g. to rename them to not have snake case in your code, then you have to use lazy, as otherwise kotlinx will try to find the views while onCreate hasn't even run yet.
m

miha-x64

02/16/2017, 1:57 PM
robin: you can try this:
class MainActivity {
    private lateinit var someView: View
    override fun onCreate(state: bundle) {
        super.onCreate();
        someView = some_view;
    }
}
r

robin

02/16/2017, 1:59 PM
Sure, but I don't like the
lateinit
modifier, and neither do I like separating initialization from declaration. I've not noticed a performance impact yet by using the lazy delegate in this situation.
m

miha-x64

02/16/2017, 2:00 PM
It’s more about memory impact.
r

robin

02/16/2017, 2:01 PM
Well I haven't profiled that yet, how much memory are we talking about for a single lazy delegate?
m

miha-x64

02/16/2017, 2:03 PM
1. Initializer — anonymous class (I don’t know how much memory it will occupy) + instance (about 16 bytes). 2. SynchronizedLazyImpl — 24 bytes, I think.
r

robin

02/16/2017, 2:10 PM
Well, I don't think that's going to be a serious problem for a few views in an activity class.
m

miha-x64

02/16/2017, 2:13 PM
You’re going to use this instead of four bytes.
r

robin

02/16/2017, 2:17 PM
I won't use this, I'm just using the kotlinx properties directly, as you originally suggested. But if I was forced to introduce a local proxy property then yes, I'll prefer the more maintainable code over the slightly more memory efficient code. But actually, I just thought of this solution:
class MainActivity {
    private val someView: View
        get() = some_view
}
How does that look to you?
m

miha-x64

02/16/2017, 2:19 PM
Looks better. Also you can eliminate this extra method by using
inline val
.
r

robin

02/16/2017, 2:19 PM
Ah, didn't know about that. Is that new in 1.1?
m

miha-x64

02/16/2017, 2:19 PM
Yes, it is.
r

robin

02/16/2017, 2:19 PM
Nice. Thanks!
m

miha-x64

02/16/2017, 2:20 PM
On 1.0.x you can try using an ordinary inline function:
inline fun someView() = some_view
.
k

kingsley

02/17/2017, 2:01 PM
@robin there's a problem with lazy. You should try and avoid it for initializing views. Since it only initializes once, you might end up referencing the wrong view, after the view hierarchy has been destroyed and recreated for instance (typically in a fragment whose view life cycle is usually different and possibly shorter than the fragment instance itself). This ends up causing leaks and very hard to debug problems in the future
r

robin

02/17/2017, 4:49 PM
@kingsley Huh, didn't think about that.