gpt4 book ai didi

scala - trait 中的覆盖函数

转载 作者:行者123 更新时间:2023-12-04 16:32:21 27 4
gpt4 key购买 nike

假设我有以下特征

trait Foo[T] {
def overrideMe(other:Foo[T]) : Int
}

我希望能够做到
class Bar extends Foo[Int] {
override def overrideMe(other:Bar) : Int = other.BarFn
}

但它不编译。原因是我希望 overrideMe 能够使用子类型的功能。我可以做类似的事情
class Bar extends Foo[Int] {
override def overrideMe(other:Foo[Int]) : Int = {
other.asInstanceOf[Bar].BarFn
}

但这看起来不太好。

是否可以在 trait 中说虚拟函数可以被子类型覆盖?

编辑
@agilesteel 这几乎可以工作,但是如果我在另一个类中有一个仅依赖于特征 Foo 的函数,我就会遇到麻烦
class Test[T] {
def callOverrideMe(a : Foo[T], b : Foo[T] ) : Int = a.overrideMe(b)
}

我收到一个编译错误:类型不匹配;发现 b.type(具有底层类型 foo.Foo[T])需要 a.SubType

最佳答案

trait Foo[T] {
type TheSubType <: Foo[T]
def overrideMe(other: TheSubType) : Int
}

class Bar extends Foo[Int] {
type TheSubType = Bar
override def overrideMe(other: Bar) : Int = other.barFn
def barFn = 10
}

关于scala - trait 中的覆盖函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7153129/

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