Adam S
11/30/2023, 9:33 AMclass Container(
val name: String,
val parent: Container?
)
// WARNING A function is marked as tail-recursive but no tail calls are found
tailrec fun Container.rootParent() : Container {
return parent?.rootParent() // WARNING Recursive call is not a tail call
?: this
}
playgroundKlitos Kyriacou
11/30/2023, 9:36 AMtailrec fun Container.rootParent() : Container {
if (parent == null) return this
return parent.rootParent()
}
Klitos Kyriacou
11/30/2023, 9:38 AMrp == null
always being false.
tailrec fun Container.rootParent() : Container {
if (parent == null) return this
val rp = parent.rootParent()
if (rp == null) return this
return rp
}
Klitos Kyriacou
11/30/2023, 9:42 AMtailrec fun Container.rootParent() : Container {
if (parent == null) return this
val rp = parent.rootParent()
return rp
}
But if you remove the val rp
and return directly, it doesn't give the warning. Seems like a limitation in the compiler's capabilities.Adam S
11/30/2023, 11:43 AMDaniel Pitts
11/30/2023, 5:18 PMtailrec fun Container.rootParent():Container = if (parent == null) this else parent.rootParent()
Ironically, IntelliJ tells me that it can be replaced with parent?.rootParent() ?: this
, but then the warning happens.Daniel Pitts
11/30/2023, 5:26 PMfun Container.rootParent() = generateSequence(this) { it.parent }.last()