I am trying to use a trait as a mixin with a case class.
case class Team(name:String)
trait WinStreak{}
and I would like to use it like so:
val team = Team("name") with WinStreak
Apparently I cannot do this. Is this because case classes use the companion object to create an instance of your class? I know the other solution would be to just extend the trait in my class def, but I would like to know if its possible to create it mixin style.
In scala, trait mixins means you can extend any number of traits with a class or abstract class. You can extend only traits or combination of traits and class or traits and abstract class. It is necessary to maintain order of mixins otherwise compiler throws an error.
Traits are compile-time external values (rather than code generated from an external source). The difference is subtle. Mixins add logic, Traits add data such as compile-time type information.
Case Classes You can construct them without using new. case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.
A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.
Because Team("name")
is actually a method call to Team.apply("name")
, which create the object inside the apply method.
Create the object using new
keyword should do the trick:
case class Team(name:String)
trait WinStreak{}
val x = new Team("name") with WinStreak
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With