我在解决以下问题时遇到问题:
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>
没有编译器警告?
最佳答案
看起来像 Kotlin 编译器问题。您可以帮助编译器并显式设置序列的类型,而不是固定的
class Node(val next: Node?) {
fun asSequence(): Sequence<Node> = sequence<Node> {
var node: Node? = this@Node;
while (node != null) {
yield(node)
node = node.next
}
}
}
关于Kotlin 序列类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260614/