在Scala中,一个trait是否可以引用它所混入的类的命名构造函数参数?下面的代码不能编译,因为ModuleDao的构造函数参数不是一个作为trait定义的val。如果我在构造函数参数前添加“val”以使其公开,它将与trait中的构造函数参数匹配,并且编译通过,但我不想将其设置为“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
实际上是私有的 -- 没有其他人可以看到它。 - Daniel C. Sobral