8

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

1 回答 1

8

如果您唯一关心的是使其成为 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
于 2011-10-10T12:21:33.300 回答