ReenteringLazyValueComputationException with recursive-ish code

Here’s a simple class where I modify the behaviour of the output function each time it is called:

class PaintingRobot {
    val turn = { direction: Int ->
        output = this.paint
    }

    val paint = { colour: Int ->
        output = this.turn
    }

    var output: (Int) -> Unit = turn
}

IntelliJ 2019.3 says: “Type checking has run into a recursive problem.”
Running build on the project reports: “Error:Kotlin: [Internal Error] org.jetbrains.kotlin.util.ReenteringLazyValueComputationException”
I tried it in play.kotlinlang.org and just get a “Service temporarily available” error: https://pl.kotl.in/D5jVzCySv

I think this should work. Right?

You should specify explicitly the type of turn and paint.

1 Like

turn and paint are declared and initialized before output, which means that the 2 lambdas have not been typed at all.
Explicit the type on the first two and let the output type be inferred.

1 Like

Thanks, that did it. This works:

class PaintingRobot {
    val turn: (Int) -> Unit = { _: Int ->
        output = this.paint
    }

    val paint: (Int) -> Unit = { _: Int ->
        output = this.turn
    }

    var output: (Int) -> Unit = turn
}

To declare a lambda, you need to explicit its type. Why is needed is easily understandable if you just think about an extension lambda. The only way to tell the compile that the lambda you are creating has a particular receiver is to declare it!

Also you can just leave var output = turn