简体   繁体   中英

Scala case classes with Mixin traits

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM