繁体   English   中英

Scala:为什么自类型特征看不到构造函数参数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM