Sum*_*uma 12 constructor scala
下面的代码给出了编译错误:
class Info(val x: String)
object Info {
val default = new Info("top")
}
case class Data(x: String) {
import Info.default
def this() = this(default.x)
}
Run Code Online (Sandbox Code Playgroud)
错误:(11,23)未找到:值默认def this()= this(default.x)
为什么default
在构造函数中看不到符号,尽管有导入?
进一步的实验表明它不仅是重要的.用def
(或偶数val
)替换导入行无济于事,但错误仍然存在:
def default = Info.default
Run Code Online (Sandbox Code Playgroud)
由于自构造函数调用的作用域(当辅助构造函数调用主构造函数时),作用域未按您预期的方式工作:
构造函数定义的签名和自构造函数调用在封闭类定义时有效的范围内进行类型检查和评估,并通过封闭类的任何类型参数和封闭类的任何早期定义进行扩充模板。
换句话说,表达式的有效范围default.x
是 Outside 的范围Data
。
这很令人困惑,因为从文本上看,该表达式看起来像是在类内部。
该规则与词法范围有关,与求值顺序无关。
您必须将导入移到类定义之外。
为了好玩,在以下情况下范围界定略有破坏:
object Playroom {
def default = "playing"
case class Toy(squeezeMsg: String = default)
object Toy {
def default = "srsly"
}
}
object Test extends App {
import Playroom._
println(Toy())
println(new Toy())
}
Run Code Online (Sandbox Code Playgroud)
这就是这个益智游戏。一般来说,apply
在同伴上使用方法更惯用(也更稳健)。