Link to constructor argument from attribute

In Scala, is it possible for the attribute to refer to the argument of the named constructor of the class into which it is mixed? The code below does not compile because the ModuleDao constructor argument is not val, as defined in the attribute. If I add val before the constructor argument to make it public, it matches the one that is in this trait and it compiles, but I would prefer not to set it as 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 { ... } 
+8
constructor scala traits
source share
1 answer

If your only concern about making it val is visibility, you can simply make val this way:

 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 
+8
source share

All Articles