【问题标题】:underscore for generic type argument produces compile error in Scala?泛型类型参数的下划线会在 Scala 中产生编译错误?
【发布时间】:2021-09-21 12:44:44
【问题描述】:

我有

trait MyBase[T <: MyBase[T]] {
  def myid: String
}

这么写


case class MyBaseContainer(myBase: MyBase[_])

MyBase 中为T 产生类型绑定错误

type arguments [_$1] do not conform to trait MyBase's type parameter bounds [T <: Playground.MyBase[T]]

写成

case class MyBaseContainer[T <: MyBase[_]](myBase: T)

编译所有错误。

为什么会这样? MyBaseContainer 的这两个签名在语义上不是等效的吗?

是否有一种语法方法可以将类型参数MyBase 约束到所需的界限,而不将T 作为类型参数传递给MyBaseContainer

【问题讨论】:

标签: scala generics type-conversion existential-type f-bounded-polymorphism


【解决方案1】:

正如 Dmytro Mitin 在 cmets 中提到的,这会起作用:

import scala.language.existentials

case class MyBase[T <: MyBase[T]] (
   myid: String
)


case class MyBaseContainer(myBase: MyBase[T] forSome {type T <: MyBase[T]})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 2021-08-06
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多