class TestLazy(val mValue: Int) {
public val value by lazy { foo() }
fun foo(): Int {
try {
return mValue
} catch(e: NullPointerException) {
// a null pointer exception will raise,but it will still return the right value
return 0
}
}
Hi guys, when I run above code with latest version(beta-4584), it will raise a null pointer exception. I tried to replace
the foo() function to return a constant, then every thing just fine(of course…)
fun foo(): Int {
return 1 // work as expected
}
I want to know what’s going wrong and how to correct it, sorry for my poor english, any help will be appreciated
Update: I know the usage of lazy delegate here looks like totally useless, so below is my exercise to advent code day7…which might answer your concern
abstract class CircuitObject() {
public val value: Int by lazy { calcOutput() }
abstract protected fun calcOutput(): Int
}
class Wire(val name: String, var src: CircuitObject?) : CircuitObject() {
override fun calcOutput(): Int {
return src!!.value
}
}
class Signal(private val mValue: Int): CircuitObject() {
override fun calcOutput(): Int {
return mValue
}
}