gpt4 book ai didi

scala - 覆盖 'val'时出现意外结果

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

在Scala 2.10.4中,给出以下类:

scala> class Foo { 
| val x = true
| val f = if (x) 100 else 200
| }
defined class Foo

以下两个示例对我来说很有意义:
scala> new Foo {}.f
res0: Int = 100

scala> new Foo { override val x = false}.f
res1: Int = 200

但是,为什么此调用不返回 100
scala> new Foo { override val x = true }.f
res2: Int = 200

最佳答案

由于val不会被多次初始化,因此x实际上是null初始化期间的false(或默认BooleanFoo),然后在扩展您的示例中的Foo的匿名类中进行初始化。

我们可以使用AnyRef更加轻松地对其进行测试:

class Foo { 
val x = ""
val f = if (x == null) "x is null" else "not null"
}

scala> new Foo { override val x = "a" }.f
res10: String = x is null

scala> new Foo {}.f
res11: String = not null

Scala FAQ中有完整的解释。摘抄:

Naturally when a val is overridden, it is not initialized more than once. So though x2 in the above example is seemingly defined at every point, this is not the case: an overridden val will appear to be null during the construction of superclasses, as will an abstract val.



避免这种情况的一种简单方法是使用延迟val或def,如果所引用的val可能会被覆盖。

另外,您可以使用 -Xcheckinit编译器标志来警告您潜在的初始化错误,例如这样。

关于scala - 覆盖 'val'时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29306979/

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