这样做:
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]
)
马丁回答说:
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
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!