How to avoid recursive type-checking problem in a tree-walking generator?

I want to create a tree-walker based on the following types:

abstract class Node(val kind: String)

class Leaf(kind: String, val payload: Any?) : Node(kind)

class Unary(kind: String, val operand: Node) : Node(kind)

class Binary(kind: String, val left: Node, val right: Node) : Node(kind)

I tried with this code:

fun nodeWalker(start: Node) = sequence<Any?> {
    fun visit(node: Node) = sequence<Any?> {
        if (node is Leaf) {
        else if (node is Unary) {
            for (uit in visit(node.operand)) {
        else if (node is Binary) {
            for (lit in visit(node.left)) {
            for (rit in visit(node.right)) {

    visit(start).forEach {

However, this fails to compile, giving the error:

Error:(15, 24) Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly

That’s the visit call in the for (uit in visit(node.operand)) { line. How can I avoid this error? Which declarations is the error message referring to? Adding a type like so: uit: Any? didn’t make any difference.

The code is at

As it says, just specify the type:

fun visit(node: Node): Sequence<Any?>

Ah - OK, thanks. I see now.