Hello guys, I learnt that Kotlin has an extension ...
# android
n
Hello guys, I learnt that Kotlin has an extension function called isinitialized used on properties declared as lateinit val. I was wondering how I could create a similar function, let's say for var I looked at the source code used to create the aforementioned method but I don't really understand it.
v
What would that "similar function" do?
Copy code
fun Any?.isInitialized() = this != null

fun main() {
    var foo: String? = null
    println(foo.isInitialized())
    foo = "bar"
    println(foo.isInitialized())
}
=>
Copy code
false
true
Or
Copy code
val Any?.initialized get() = this != null

fun main() {
    var foo: String? = null
    println(foo.initialized)
    foo = "bar"
    println(foo.initialized)
}
b
Yeah, there's no value prop there IMO, checking for null is more readable and understandable when we're not talking lateinit
n
Maybe I didn't put the question properly. If I understand correctly, an extension function would work on any class from which it is created. The val and var keywords aren't classes but somehow an extension function (isinitialized) was created and it works on only variables declared with val keyword. How does that work?
a
The extension function isn't defined directly to the
var
/
val
. Its defined against
KProperty0<*>
. If you notice, to check if a property is initialized, you have to
Copy code
lateinit var lazyProp: String
fun check() {
    ::lazyProp.isInitialized
    // ::lazyProp returns KProperty<String>
}
👍 1
n
Oh now I understand, Thanks. I wasn't really sure what the "::" keyword did there, I thought it was only use for passing standards functions as lamdas.