从特征引用构造函数参数

时间:2011-10-10 12:11:27

标签: scala constructor scala-2.9 traits

在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 { ... }

1 个答案:

答案 0 :(得分:8)

如果您唯一担心的是可见性,那么您可以像这样保护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
相关问题