简体   繁体   English

具有Mixin特征的Scala案例类

[英]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. 我知道另一个解决方案是在我的类def中扩展特性,但我想知道是否有可能创建它的mixin风格。

Because Team("name") is actually a method call to Team.apply("name") , which create the object inside the apply method. 因为Team("name")实际上是对Team.apply("name")的方法调用,它在apply方法中创建对象。

Create the object using new keyword should do the trick: 使用new关键字创建对象应该做的诀窍:

case class Team(name:String)
trait WinStreak{}

val x = new Team("name") with WinStreak

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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