Waseem
09/08/2023, 2:45 PMfun KProperty0<*>.doIfInitialized(block: () -> Unit) {
// todo how to do this????
}
CLOVIS
09/08/2023, 2:57 PMinline fun <T> KProperty0<T>.ifInitialized(block: (T) -> Unit) {
if (isInitialized) {
block(get())
}
}
but the compiler doesn't allow calling isInitialized
on a generic property, because the compiler doesn't allow calling isInitialized
on a non-lateinit
property:
lateinit var a: String
var b: String = "foo"
println(::a.isInitialized)
println(::b.isInitialized) // compile error: This declaration can only be called on a reference to a lateinit property
Since there is no way to know statically if KProperty0
is a lateinit
or not, the compiler cannot allow calling it on a given instance.CLOVIS
09/08/2023, 3:00 PMinline fun <T> @receiver:AccessibleLateinitPropertyLiteral KProperty0<T>.ifInitialized(block: (T) -> Unit) {
if (isInitialized) {
block(get())
}
}
but you can't, because kotlin.internal.AccessibleLateinitPropertyLiteral
is not public.
However, the standard library could probably add this function if the maintainer wanted to.Ayfri
09/08/2023, 5:12 PMCLOVIS
09/08/2023, 5:25 PM::a.ifInitialized {
println(a)
}
if (a::isInitialized) {
println(a)
}
Not everything needs syntax sugarArun Sudharsan
09/09/2023, 11:46 AMCLOVIS
09/09/2023, 5:27 PMif
?Arun Sudharsan
09/13/2023, 6:59 PMvariable.ifInitialised { }
looks better to me than if(::variable.isInitialised) {}
CLOVIS
09/13/2023, 8:39 PMvariable.ifInitialized
, as most it would be ::variable.ifInitialized