gpt4 book ai didi

Kotlin 序列类型推断

转载 作者:行者123 更新时间:2023-12-01 00:12:03 24 4
gpt4 key购买 nike

我在解决以下问题时遇到问题:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com