Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: pre-initialize val while extending a class

How do I pre-initialize a val and extend a class in Scala?

e.g.:

object Start {
  def main(args: Array[String]): Unit = {
        new T()
        new T2()
        //T3?
  }
}

class T extends{val z = 10} with X  with Y
class T2 extends X with Y {val z=10}
//class T3 extends{val z = 10}  ??? Z with X with Y //????

class Z

trait  X {
  val z :Int
}

trait Y { this :X =>
  println("Test: "+z)  
}
like image 499
Stefan K. Avatar asked May 02 '13 20:05

Stefan K.


1 Answers

Use:

class T3 extends {val z = 10} with Z with X with Y

Scala Language Specification 2.9, 5.1.6:

EarlyDefs ::= ‘{’ [EarlyDef {semi EarlyDef}] ‘}’ ‘with’

So an early definition always has to be followed by a with

like image 176
gzm0 Avatar answered Sep 19 '22 18:09

gzm0