Alexander Arendar
Alexander Arendar

Reputation: 3435

How to mix in two traits when instantiating a case class instance?

Here goes my REPL session:

scala> case class Person(name:String)
defined class Person

scala> trait Hobby{val hobby:String}
defined trait Hobby

scala> trait ProgrammingLanguage{val language:String}
defined trait ProgrammingLanguage

scala> val alex = new Person("Alex") with Hobby{val hobby:String = "fishing"}
alex: Person with Hobby = Person(Alex)


scala> val alex2 = new Person("Alex") with Hobby{val hobby:String = "fishing"} with ProgrammingLanguage{val language:String = "Scala"}
<console>:1: error: ';' expected but 'with' found.
       val alex = new Person("Alex") with Hobby{val hobby:String = "fishing"} with ProgrammingLanguage{val language:String = "Scala"}

I don't exactly understand why I can mix one trait but cannot mix two of them in such way. Could you explain?

Upvotes: 1

Views: 63

Answers (1)

Sebastian
Sebastian

Reputation: 17443

In your example you are trying to define two bodies for the instance of Person. This is not possible. You need to define both hobby and language in the same body:

val alex2 = new Person("Alex") with Hobby with ProgrammingLanguage {
  val hobby:String = "fishing"
  val language:String = "Scala"
}

Upvotes: 3

Related Questions