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) {
yield(node.payload)
}
else if (node is Unary) {
for (uit in visit(node.operand)) {
yield(uit)
}
}
else if (node is Binary) {
for (lit in visit(node.left)) {
yield(lit)
}
for (rit in visit(node.right)) {
yield(rit)
}
}
}
visit(start).forEach {
yield(it)
}
}
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