I'm looking for a way to prevent problems in Kotlin with the order of property initialization. One of my biggest loves of Kotlin is all the ways you can lean on the compiler to prevent errors. But in this case it falls flat. Here's an example
class Test{
val b = computeB()
val a = computeA()
private fun computeA() = 4
private fun computeB() = a + 1
}
fun main(args: Array<String>) {
val a = Test()
println("value of b: " + a.b)
println("value of a: " + a.a)
}
In this scenario, you get a = 4 and b = 1. But you should get b = 5. I understand what's going on, a is not initialized yet so it defaults to 0 when it's accessed. I was hoping that Kotlin would at least throw an exception to let me know.
This is a trivial example, but in large classes with lots of code it's easy to accidentally do this. My question is, what is the best style/paradigm/pattern that I can use in Kotlin to ensure this kind of mistake doesn't happen. I'm looking for some sort of rule that I can hold myself, and my teammates to. Like "you should construct properties in this way, because otherwise you open the door to these kinds of bugs".