依赖于 trait 中 case 类的方法 [英] rely on methods of case class in trait

查看:55
本文介绍了依赖于 trait 中 case 类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法依赖在 trait 中的 case 类中定义的方法?例如,复制:以下不起作用.不过我不知道为什么.

Is there a way to rely on methods defined in case class in a trait? E.g., copy: the following doesn't work. I'm not sure why, though.

trait K[T <: K[T]] {
  val x: String
  val y: String
  def m: T = copy(x = "hello")
  def copy(x: String = this.x, y: String = this.y): T
}

case class L(val x: String, val y: String) extends K[L]

给出:

error: class L needs to be abstract, since method copy in trait K of type 
(x: String,y: String)L is not defined
           case class L(val x: String, val y: String) extends K[L]
                      ^

推荐答案

我想在 trait 中具有名称为 copy 的方法指示编译器不在 case class 中生成方法副本 - 因此在您的示例中方法副本未在您的情况下实现班级.下面是在 trait 中实现的方法复制的简短实验:

I suppose that having method with name copy in trait instructs compiler to not generate method copy in case class - so in your example method copy is not implemented in your case class. Below short experiment with method copy implemented in trait:

scala> trait K[T <: K[T]] {                                                                                   
     | val x: String                                                                                          
     | val y: String                                                                                          
     | def m: T = copy(x = "hello")                                                                           
     | def copy(x: String = this.x, y: String = this.y): T = {println("I'm from trait"); null.asInstanceOf[T]}
     | }

defined trait K

scala> case class L(val x: String, val y: String) extends K[L]                                                
defined class L

scala> val c = L("x","y")                                                                                     
c: L = L(x,y)

scala> val d = c.copy()                                                                                       
I'm from trait
d: L = null

这篇关于依赖于 trait 中 case 类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆