【发布时间】:2011-10-10 12:11:27
【问题描述】:
在 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 { ... }
【问题讨论】:
-
为什么不将其设置为
val?您已经在Daoism上这样做了,那么为什么不在ModuleDao上这样做呢?问题在于,您声明sessionFactory的方式实际上是私有的——其他人无法看到它。
标签: scala constructor scala-2.9 traits