bod
06/30/2020, 11:33 AMval which is initialized in init , but the super's init calls a method that accesses it (so: before it's initialized). In that method I can do a if (myVar != null) { ... which works. But now I get a Unnecessary safe call on a non-null receiver warning π The compiler tells me this null check is useless since this val is non nullable... But here it can be null.
I can of course ignore / suppress the warning but I was wondering if there's a deeper truth to this π
Ideas?arjun
06/30/2020, 11:43 AMbod
06/30/2020, 11:44 AMbod
06/30/2020, 11:52 AMopen class Parent {
init {
doStuff()
}
open fun doStuff() {}
}
class Child : Parent() {
private val s: String
init {
s = "Hello, World!"
}
override fun doStuff() {
println(s?.length) // <- warning here because `?.` on something supposedly non nullable (but null)
}
}bod
06/30/2020, 11:54 AMinit calling non final doStuff. But in my case Parent doesn't belong to me (it's actually an Android framework's class)louiscad
06/30/2020, 11:56 AMarjun
06/30/2020, 11:58 AMlouiscad
06/30/2020, 11:59 AMinit block of Parent is called before the one of Child.Michael de Kaste
06/30/2020, 12:03 PMMichael de Kaste
06/30/2020, 12:04 PMprivate val s: String? right?bod
06/30/2020, 12:04 PM?. was a "workaround"bod
06/30/2020, 12:06 PMinit gives the impression that in can never be null indeedMichael de Kaste
06/30/2020, 12:10 PMclass Child : Parent() {
override fun doStuff() {
println(s.length)
}
companion object {
private const val s: String = "Hello World"
}
}bod
06/30/2020, 12:32 PMbod
06/30/2020, 12:33 PMMichael de Kaste
06/30/2020, 12:40 PMbod
06/30/2020, 12:41 PMfindViewById.) So a val but definitely not random nor static πMichael de Kaste
06/30/2020, 12:47 PMclass Child : Parent() {
val s: String
get() = "Hello World"
override fun doStuff() {
println(s.length)
}
}Michael de Kaste
06/30/2020, 12:50 PMlouiscad
06/30/2020, 12:51 PMlazy(NONE) { }bod
06/30/2020, 12:53 PMbod
06/30/2020, 12:53 PMbod
06/30/2020, 12:55 PMinit is very useful and shouldn't be ignored! - even though in my case it's "not my fault" as this happens in the framework π)