gpt4 book ai didi

scala - 具有逆变类型参数的继承返回类型

转载 作者:行者123 更新时间:2023-12-01 23:54:39 25 4
gpt4 key购买 nike

我有一个具有协变类型 A 的特征,它声明(除其他外)这个方法:

sealed trait MaxPQ[+U] {
...
def insert[K >: U : Ordering](v: K): this.type
...
}

abstract class AbstractMaxPQ[U : Ordering] extends MaxPQ[U]

我还需要使用这个混音:

trait FindMin[U] {

self: AbstractMaxPQ[U] =>

我要返回 this.type 因为我希望基于 NodeArray 的优先级队列实现返回当前类型而不是 MaxPQ[U].

在基于数组的实现中,我有以下内容:

class ArrayMaxPQ[U : Ordering : ClassTag] ...extends AbstractMaxPQ[U] with FindMin[U]{
...
override def insert[K >: U : Ordering](v: K): ArrayMaxPQ[U] = ???
...

这是我的 IDE 自动生成的。当然我需要这个方法来返回ArrayMaxPQ[K]this.type 不接受类型参数。在这里使用更高级的类型也是行不通的

def insert[K >: U : Ordering, G[_] <: MaxPQ[_]](v: K): G[K]

因为 G 不能用 self 类型在 child 中进行参数化。

我有点困惑,因为这感觉像是一个简单的要求,但我找不到实现它所需的语言功能/语法。

最佳答案

也许您希望返回类型比 this.type 宽,但比 MaxPQ[U] 窄。然后尝试引入类型成员

sealed trait MaxPQ[+U] {
type This <: MaxPQ[U]
// type This >: this.type <: MaxPQ[U] { type This = MaxPQ.this.This }

def insert[K >: U : Ordering](v: K): This
}

abstract class AbstractMaxPQ[U : Ordering] extends MaxPQ[U] {
override type This <: AbstractMaxPQ[U]
// override type This >: this.type <: AbstractMaxPQ[U] { type This = AbstractMaxPQ.this.This }
}

class ArrayMaxPQ[U : Ordering : ClassTag] extends AbstractMaxPQ[U] {
override type This = ArrayMaxPQ[U]

override def insert[K >: U : Ordering](v: K): ArrayMaxPQ[U] = ???
}

Returning the "Current" Type in Scala


如果你想用 U 的上限对返回类型进行参数化,请尝试使 This higher-kinded

sealed trait MaxPQ[+U] {
type This[K >: U] <: MaxPQ[K]
// type This[K >: U] <: MaxPQ[K] { type This[K1 >: K] = MaxPQ.this.This[K1] }

def insert[K >: U : Ordering](v: K): This[K]
}

abstract class AbstractMaxPQ[U : Ordering] extends MaxPQ[U] {
override type This[K >: U] <: AbstractMaxPQ[K]
// override type This[K >: U] <: AbstractMaxPQ[K] { type This[K1 >: K] = AbstractMaxPQ.this.This[K1] }
}

class ArrayMaxPQ[U : Ordering : ClassTag] extends AbstractMaxPQ[U] {
override type This[K >: U] = ArrayMaxPQ[K]

override def insert[K >: U : Ordering](v: K): ArrayMaxPQ[K] = ???
}

关于scala - 具有逆变类型参数的继承返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62986446/

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