This is the code snippet:
abstract class SuperClass {
init {
toOverride()
}
abstract fun toOverride()
}
class ChildClass : SuperClass() {
private val innerClass = InnerClass()
override fun toOverride() {
innerClass.doSomething()
}
class InnerClass {
fun doSomething() = Unit
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val superClass = ChildClass()
superClass.toOverride()
}
}
Calling superClass.toOverride() will cause null pointer exception but from ChildClass point of view innerClass is an immutable field. The problem is that in the constructor of SuperClass toOverride() is being called.
We don't have control over how SuperClass is written in a lot of cases. In android framework there is a lot of such cases, for example http://androidxref.com/8.0.0_r4/xref/frameworks/base/core/java/android/view/View.java#20160 will be called in the constructor of View.java. How do we address those issues? Adding null checks will trigger IDE warning and looks like kotlin compiler will trim the null check sometimes if you use ?. operator since it think the ?. is not necessary.