F-Bounded 多态类型和非泛型子类型的存在类型?
Existential types for F-Bounded Polymorphic types and non-generic subtypes?
我有两个子类型需要通过类型 A
和其中一个子类型的子类型进行 F 界多态,即
trait A[T <: A[T]] {
def x: T
}
trait Ter extends A[Ter]
trait For extends A[For]
trait C extends Ter
接下来我尝试实现一个具体的类型
case class F2(l: List[A[_]]) extends For {
def x: For = F2(l.map(_.x))
}
但是编译失败:
<console>:11: error: type mismatch;
found : List[Any]
required: List[A[_]]
def x: For = F2(l.map(_.x))
^
所以,google 说我需要使用存在类型,这是有道理的,所以我尝试:
import scala.language.existentials
type SomeA = T forSome { type T <: A[T] }
case class F1(l: List[SomeA]) extends For {
def x: For = F1(l.map(_.x))
}
但是,现在我在尝试实例化时遇到了一个新问题
trait Example {
val b: Ter
val c: C
val d: For
// Works fine
val l1: List[A[_]] = List(b, c, d)
// But this doesn't work, fails to compile (see below)
val l2: List[SomeA] = List(b, c, d)
val f1 = F1(l2)
}
编译错误:
<console>:22: error: type mismatch;
found : C
required: SomeA
(which expands to) T forSome { type T <: A[T] }
val l2: List[SomeA] = List(b, c, d)
^
为什么会出现此错误?肯定 C
是 Ter
的子类型,而 Ter
又是 A[Ter]
的子类型,因此 C
是 A[Ter]
的子类型,因此存在 T
即 Ter
这样 C
是 A[T]
的子类型,因此 C
是 SomeA
.
的子类型
好像子类型的传递性不起作用。当我用 c.asInstanceOf[SomeA]
破解它时,我的代码编译通过了单元测试。会不会是编译器错误?
我还认为 List[A[_]]
的输入比 List[SomeA]
强,即前者说列表由 A[T]
一些 固定 组成输入 T
,后者表示列表由 A[T]
组成,其中 T
是 not fixed.
BOUNS 如果你能解释 为什么 当前接受的答案有效,即为什么编译器无法计算出类型有效归属。
我想编译器需要一些帮助。以下应该有效:
val l2 = List[SomeA](b, c: Ter, d)
我有两个子类型需要通过类型 A
和其中一个子类型的子类型进行 F 界多态,即
trait A[T <: A[T]] {
def x: T
}
trait Ter extends A[Ter]
trait For extends A[For]
trait C extends Ter
接下来我尝试实现一个具体的类型
case class F2(l: List[A[_]]) extends For {
def x: For = F2(l.map(_.x))
}
但是编译失败:
<console>:11: error: type mismatch;
found : List[Any]
required: List[A[_]]
def x: For = F2(l.map(_.x))
^
所以,google 说我需要使用存在类型,这是有道理的,所以我尝试:
import scala.language.existentials
type SomeA = T forSome { type T <: A[T] }
case class F1(l: List[SomeA]) extends For {
def x: For = F1(l.map(_.x))
}
但是,现在我在尝试实例化时遇到了一个新问题
trait Example {
val b: Ter
val c: C
val d: For
// Works fine
val l1: List[A[_]] = List(b, c, d)
// But this doesn't work, fails to compile (see below)
val l2: List[SomeA] = List(b, c, d)
val f1 = F1(l2)
}
编译错误:
<console>:22: error: type mismatch;
found : C
required: SomeA
(which expands to) T forSome { type T <: A[T] }
val l2: List[SomeA] = List(b, c, d)
^
为什么会出现此错误?肯定 C
是 Ter
的子类型,而 Ter
又是 A[Ter]
的子类型,因此 C
是 A[Ter]
的子类型,因此存在 T
即 Ter
这样 C
是 A[T]
的子类型,因此 C
是 SomeA
.
好像子类型的传递性不起作用。当我用 c.asInstanceOf[SomeA]
破解它时,我的代码编译通过了单元测试。会不会是编译器错误?
我还认为 List[A[_]]
的输入比 List[SomeA]
强,即前者说列表由 A[T]
一些 固定 组成输入 T
,后者表示列表由 A[T]
组成,其中 T
是 not fixed.
BOUNS 如果你能解释 为什么 当前接受的答案有效,即为什么编译器无法计算出类型有效归属。
我想编译器需要一些帮助。以下应该有效:
val l2 = List[SomeA](b, c: Ter, d)