Lazy initialisation
You could make the properties non-nullable with lateinit var
.
This would prevent the need for any null checks.
You can check to see if the properties are present with isInitialized
instead of a non-null check.
class Sample {
lateinit var variable1: SomeClass
lateinit var variable2: SomeClass
lateinit var variable3: SomeClass
fun checkVariable() {
when {
// so long as a value is initialised, there is no need for null checks
::variable1.isInitialized -> variable1.printName()
::variable2.isInitialized -> variable2.printName()
::variable3.isInitialized -> variable3.printName()
}
}
}
class SomeClass(val name: String) {
fun printName() {
println(name)
}
}
Unsetting values
This can be useful to avoid null checks, but it would prevent 'unsetting' previously set variables with null
.
val sample = Sample()
sample.variable1 = SomeClass("foo")
sample.variable1 = null // ERROR: Null can not be a value of a non-null type SomeClass
Whether unsetting values is required or not depends on your use-case.
Example
fun main() {
val sample = Sample()
println("first check:")
sample.checkVariable()
println("---")
sample.variable3 = SomeClass("Jamie")
println("second check:")
sample.checkVariable()
println("---")
sample.variable2 = SomeClass("Maddie")
println("third check:")
sample.checkVariable()
println("---")
sample.variable1 = SomeClass("Lisa")
println("fourth check:")
sample.checkVariable()
println("---")
}
We can see that as each variable is set, other variables are not called, as they are listed lower in the when
statement.
first check:
---
second check:
Jamie
---
third check:
Maddie
---
fourth check:
Lisa
---