gpt4 book ai didi

scala:为什么下划线 (_) 初始化适用于字段而不适用于方法变量?

转载 作者:行者123 更新时间:2023-12-04 00:53:46 25 4
gpt4 key购买 nike

这有效:

scala> class foo[T] {
| var t: T = _
| }
defined class foo

但这不是:
scala> def foo[T] = {
| var t: T = _
| }
<console>:5: error: local variables must be initialized
var t: T = _

为什么?

(一个可以使用:
var t: T = null.asInstanceOf[T]

)

最佳答案

a mailing list thread马丁回答说:

It corresponds to the JVM. You can omit a field initialization but not a local variable initialization. Omitting local variable initializations means that the compiler has to be able to synthesize a default value for every type. That's not so easy in the face of type parameters, specialization, and so on.



当被问及在 Scala 合成默认值的问题上字段和局部变量之间如何或应该有任何区别时,他继续说:

In terms of bytecodes there IS a clear difference. The JVM will initialize object fields by default and require that local variables are initialized explicitly. […] I am not sure whether we should break a useful principle of Java (locals have to be initialized before being used), or whether we should rather go the full length and introduce flow-based initialization checking as in Java. That would be the better solution, IMO, but would require significant work in terms of spec and implementation. Faced with these choices my natural instinct is to do nothing for now :-)



因此,如果我理解正确的话,Scala 编译器实际上并没有合成对象字段的默认值,它会生成字节码,让 JVM 来处理这个问题。

根据 SI-4437 Martin 同意实际认可 null.asInstanceOf[T]语言规范中的模式,似乎是因为无法在现有约束内切实支持更好的替代方案。

关于scala:为什么下划线 (_) 初始化适用于字段而不适用于方法变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1598712/

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