Reputation: 302
I have the following:
scala> trait Tail
scala> case class Cat(name: String)
scala> val aa = new Cat(name = "bob")
val aa: Cat with Tail = Cat(ben)
scala> val bb = aa.copy(name = "ted")
val bb: Cat = Cat(ted)
Why is it that bb
didn't inherited the Tail
trait?
How can I copy aa
and still preserve the trait?
Upvotes: 2
Views: 505
Reputation: 170735
val aa: Cat with Tail = Cat(ben)
Given the line above, this shouldn't happen. I assume you instead had
scala> val aa = new Cat(name = "ben") with Tail
In this case, it inherits copy
from Cat
, and the definition is given in Scala Language Specification. Following it, you can see that aa.copy("ted")
just calls the constructor and returns new Cat("ted")
.
If you want to return Cat with Tail
, you could implement it manually:
val aa = new Cat(name = "ben") with Tail {
override def copy(name: String): Cat with Tail = new Cat(name) with Tail
}
or declare a separate class, but there's no built-in support. If you made the subclass a case class, it would get its own copy
method, but a case class can't extend a case class; so in that case, Cat
shouldn't be a case class.
Upvotes: 1