0

So, what I want to do is to create an abstract inheritance model using traits. I think example code works best so I created this small showcase to present my problem.

trait Animals{
 val owned: Seq[Animal]
 type Animal <: TAnimal
 trait TAnimal {
  def name : String
 }
}

So far so good. Now I have another trait "Dogs". The dogs are chipped so they have and identification Number. Also I want to implement the sequence containing all the dogs I have (lets say I have 5 dogs with random names and random identNo, for simplicities sake).

trait Dogs extends Animals{
 type Dog <: TDog
 val owned = ???
 trait TDog extends TAnimal {
  def identNo : Int
 }
}

The Problem is, since Animal or Dog are only types I cannot create concrete instances of them. I think I can use something like Seq.fill but I'm not able to create a matching expression.

1 Answer 1

2

This is called a Cake Pattern. And you don't need to write all this stuff in Dog trait, you can define it like this:

trait Animals{
 type Animal <: TAnimal
 def owned: Seq[Animal]
 trait TAnimal {
  def name : String
 }
}

trait Dogs extends Animals{
 type Animal <: TDog
 trait TDog extends TAnimal {
  def identNo : Int
 }
}

Then "at the end of the world" you assemble your cake with some concrete implementation:

trait ReservoirDogs extends Dogs {
  case class Animal(name: String, identNo: Int) extends TDog
  val owned = List(Animal("Pink", 1), Animal("Blue", 2))
}

Now you can mix it in:

scala> val dogs = new Dogs with ReservoirDogs {}
dogs: Dogs with ReservoirDogs = $anon$1@6f6f6727

scala> val dogs = new Animals with ReservoirDogs {}
dogs: Animals with ReservoirDogs = $anon$1@11c8ce34

This is what Cake Pattern is all about

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that really helped. Didn't knew about the Cake Pattern so far. Btw. I really like your example =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.