我遇到了以下问题,无法解决:
class Node(val next: Node?) {
fun asSequence(): Sequence<Node> = sequence {
var node: Node? = this@Node;
while (node != null) {
yield(node)
node = node.next
}
}
}
编译器显然失败了:
Type inference failed. Expected type mismatch: inferred type is Sequence<Node?> but Sequence<Node> was expected
我希望序列是
Sequence<Node>
,而不是Sequence<Node?>
,这应该是可能的,因为yield()
在一个空检查后面。当我将
yield(node)
更改为yield(node!!)
或yield(node as Node)
时,类型推断可以工作,但现在我会收到编译器警告:Unnecessary non-null assertion (!!) on a non-null receiver of type Node
如何创建一个没有编译器警告的
Sequence<Node>
?