Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala case classes with Mixin traits

Tags:

scala

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.

like image 608
Dan_Chamberlain Avatar asked Apr 24 '11 01:04

Dan_Chamberlain


People also ask

What is a trait Mixins in scala?

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.

What is the difference between a trait and a mixin?

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.

Can scala case class have methods?

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.

For which kind of data should you use a case class in scala?

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.


1 Answers

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
like image 76
Brian Hsu Avatar answered Sep 24 '22 03:09

Brian Hsu