gpt4 book ai didi

scala - 澄清为什么我不能通过它的子类型覆盖使用泛型类参数的方法

转载 作者:行者123 更新时间:2023-12-04 02:35:11 25 4
gpt4 key购买 nike

给定以下情况 ( scastie )

trait Element
class Earth extends Element

trait Container[T]
class ContainerEarth extends Container[Earth]

trait Dummy[E <: Element] {

def dummy(container: Container[E]): Any
}

class EarthDummy extends Dummy[Earth] {

def dummy(container: ContainerEarth): Any = ??? // could not override
override def dummy(container: Container[Earth]): Any = ???
}

我仍然不清楚为什么 ContaineEarth 无法覆盖。

我有解决业务问题的解决方案,但我需要了解为什么编译器拒绝替换。

trait Dummy[E <: Element, C <: Container[E]] {

def dummy(container: C): Any
}

我知道游戏中存在差异,并阻止它。

但对我来说,差异是关于Container[Dirt]Container[Earth] 的子类型,如果Dirt 延伸Earth Container 通用参数是协变的。

所以我愿意接受您的所有澄清。

最佳答案

性状 Dummy[E <: Element]描述了一个契约(Contract)。实现此特征的类必须具有方法 dummy接受任意container: Container[E] .

DirtDummy 是一个 Dummy[Earth] .所以它的方法dummy必须接受任意 container: Container[Earth] .如果它只接受 ContainerEarth它无法处理 container类型为 Container[Earth]但没有类型 ContainerEarth :

class AnotherContainerEarth extends Container[Earth]

new DirtDummy().dummy(new AnotherContainerEarth)

所以这将违反契约(Contract)。

当您定义 def dummy(container: ContainerEarth): Any 时这不是压倒一切,而是重载。

关于scala - 澄清为什么我不能通过它的子类型覆盖使用泛型类参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62286946/

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