开发者

Scala case classes with Mixin traits

开发者 https://www.devze.com 2023-02-28 14:17 出处:网络
I am trying to use a trait as a mixin with a case class. case class Team(name:String) trait WinStreak{}

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
0

精彩评论

暂无评论...
验证码 换一张
取 消