依赖特质案例类的方法

问题描述 投票:16回答:3

有没有办法依赖特征中case类中定义的方法?例如,副本:以下不起作用。不过,我不知道为什么。

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]
                      ^
scala case-class
3个回答
4
投票

我想在trait中使用名称副本的方法指示编译器不在case类中生成方法副本 - 所以在你的示例方法中,copy类没有在你的case类中实现。以下是在特征中实现方法复制的简短实验:

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

14
投票

解决方案是声明必须使用复制方法将特征应用于类:

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

(遗憾的是,您不能在复制方法中使用隐式参数,因为类型声明中不允许使用隐式声明)

然后你的声明是好的:

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

(在REPL scala 2.8.1中测试)

您的尝试不起作用的原因在其他用户提出的解决方案中进行了解释:您的copy声明阻止了“case copy”方法的生成。


1
投票

您可以使用$ scala -Xprint:typer运行repl。使用参数-Xprint:typer,您可以查看创建特征或类时究竟发生了什么。并且您将从输出中看到未创建方法“copy”,因此编译器请求自己定义它。

© www.soinside.com 2019 - 2024. All rights reserved.