加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 19:09:25 所属栏目:安全 来源:网络整理
导读:这样做: 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] )
这样做:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读