gpt4 book ai didi

scala - 依靠特征中的案例类方法

转载 作者:行者123 更新时间:2023-12-03 14:05:10 25 4
gpt4 key购买 nike

有没有一种方法可以依赖特征中案例类中定义的方法?例如,复制:以下内容无效。我不知道为什么。

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]
^

最佳答案

我想在特征中具有名称复制的方法会指示编译器不要在case类中生成方法副本-因此在您的示例中,方法副本未在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

关于scala - 依靠特征中的案例类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5341120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com