[英]Scala: Why can self-typed traits not see constructor args
为什么没有在类的主体中定义它就看不到构造函数 arg myval ? 例如,trait 无法看到构造函数 arg,如下所示:
scala> class A(myval: String){}
scala> trait B {
| this: A =>
| println(myval)
| }
<console>:8: error: not found: type A
this: A =>
^
<console>:9: error: not found: value myval
println(myval)
^
我必须在类的主体中再次声明构造函数 arg。
scala> class A(_myval: String){ val myval = _myval}
defined class A
scala> trait B {
| this: A =>
| println(myval)
| }
defined trait B
有人可以帮我理解为什么会这样吗?
这是因为class
在默认情况下没有定义 getter,因此您无法访问myval
。
如果你这样做:
class A(_myval:String) {
def myval = _myval
}
trait B {
this : A => println(myval)
}
这有效。
您的示例将“按原样”与case class
因为然后将自动构建 getter。
编辑:根据 Rob Starling 的评论,您可以将类定义缩短为class A(val myval:String)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.