0

Is it possible to initialize an attribute in an enclosed trait of a cake pattern? Something similar to early initializers. For example:

object CakePatternInit {

  trait A {
    var prop: String = null
  }

  trait A1 extends A

  trait B {
    this: A =>
    println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc"
  }

  def main(args: Array[String]) {

    val b = new B with A1
    //  how do I initialize prop here?
    //  can I write something like this:
    //  val b = new B with { prop = "abc" } A1
  }
}
Adrian
  • 3,762
  • 2
  • 31
  • 40
  • How about this: http://stackoverflow.com/questions/35359022/scala-trait-member-initialization-use-traits-to-modify-class-member/35359899#35359899 – yǝsʞǝla Feb 25 '16 at 08:26

1 Answers1

1
  trait A {
    def prop: String
  }

  trait A1 extends A

  trait B {
    this: A =>
    println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc"
  }

  val t = new B with A1 { def prop = "Hello"}
  > HELLO
  > t.prop
  res22: String = Hello

Declare your prop as method, because scala can't override var's

There is an article that can help you: cake pattern

Adrian
  • 3,762
  • 2
  • 31
  • 40
chengpohi
  • 14,064
  • 1
  • 24
  • 42