gpt4 book ai didi

scala - 参数列表中的类型推断结合 setter 不起作用

转载 作者:行者123 更新时间:2023-12-04 12:42:10 26 4
gpt4 key购买 nike

让我们想象一下范围内的以下项目:

object Thing { 
var data: Box[String] = Empty
}

def perform[T](setter: Box[T] => Unit) {
// doesn't matter
}

以下无法编译:
perform(Thing.data = _)

错误信息是:
<console>:12: error: missing parameter type for expanded function ((x$1) => Thing.data = x$1)
perform(Thing.data = _)
^
<console>:12: warning: a type was inferred to be `Any`; this may indicate a programming error.
perform(Thing.data = _)
^

虽然以下编译:
perform(Thing.data_=)

我已经通过创建更好的抽象超越了这个问题,但我的好奇心仍然存在。

谁能解释这是为什么?

最佳答案

让我们扩展您在第一个示例中所做的事情:

Thing.data = _

是定义匿名函数的简写,如下所示:
def anon[T](x: Box[T]) {
Thing.data = x
}

所以当你打电话
perform(Thing.data = _)

它和
perform(anon)

问题是 anonperform取一个类型参数 T并且您绝不会声明什么 T是。编译器只能从传递的参数中推断函数调用中的类型参数,而不能从函数体内部推断出类型参数,因此无法在 anon 中推断出类型参数。那个 T应该是 String .

请注意,如果您调用
perform[String](Thing.data = _)

编译器没有问题,因为它现在知道什么 T应该是,如果你尝试使用除字符串之外的任何类型,你会得到一个类型不匹配错误,但错误发生在匿名函数的主体中,而不是在调用 perform 时发生。 .

然而,当你打电话
perform(Thing.data_=)

您正在传递方法 Thing.data_= ,明确定义为 Box[String] => Unit ,因此编译器可以推断 perform的类型参数,因为它来自函数参数。

关于scala - 参数列表中的类型推断结合 setter 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982847/

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