Nic*_*ick 8 constructor scala traits scala-2.9
在Scala中,特征是否有可能引用它所混合的类的命名构造函数参数?下面的代码无法编译,因为ModuleDao的构造函数参数不是特征中定义的val.如果我val在构造函数参数之前添加它以使其公开,它与特征中的那个匹配并且它编译,但我不想将其设置为val.
trait Daoisms {
val sessionFactory:SessionFactory
protected def session = sessionFactory.getCurrentSession
}
class ModuleDao(sessionFactory:SessionFactory) extends Daoisms {
def save(module:Module) = session.saveOrUpdate(module)
}
/* Compiler error:
class ModuleDao needs to be abstract, since value sessionFactory in trait Daoisms of type org.hibernate.SessionFactory is not defined */
// This works though
// class ModuleDao(val sessionFactory:SessionFactory) extends Daoisms { ... }
Run Code Online (Sandbox Code Playgroud)
如果您只关心将其设为val是可见性,那么您可以像这样保护val:
scala> trait D { protected val d:Int
| def dd = d
| }
defined trait D
scala> class C(protected val d:Int) extends D
defined class C
scala> new C(1)
res0: C = C@ba2e48
scala> res0.d
<console>:11: error: value d in class C cannot be accessed in C
Access to protected value d not permitted because
enclosing class object $iw in object $iw is not a subclass of
class C in object $iw where target is defined
res0.d
^
scala> res0.dd
res2: Int = 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2559 次 |
| 最近记录: |