【问题标题】:Type bound error when creating a tuple in scala在 scala 中创建元组时类型绑定错误
【发布时间】:2019-02-26 17:02:16
【问题描述】:

假设我有一个类型

trait Mode[T]
trait MyType[T, M <: Mode[T]]

这样编译

val t: MyType[_, _] = ???
t

但不是这个

val t: MyType[_, _] = ???
"some_string" -> t

错误提示类似于type arguments [_$0,_$1] do not conform to trait MyType's type parameter bounds

所以我的问题是为什么这不能在创建元组时编译?

【问题讨论】:

标签: scala existential-type


【解决方案1】:

实际上t"some string" -&gt; t 都会在运行时出现同样的问题:

import scala.language.existentials
import scala.reflect.runtime.universe._

type SubMode[T] = M forSome { type M <: Mode[T] }

val t: MyType[_, _] = new MyType[String, SubMode[String]] {}
// t: MyType[_, _] = $anon$1@596afb2f

"some string" -> t
// error: type arguments [_$1,_$2] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]

reify(t)
// error: type arguments [_$1,_$2] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]

reify("some string" -> t)
// error: type arguments [_$1,_$2] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]

事实上,编译时的问题并不特定于元组。例如:

List(t)
// error: type arguments [_$1,_$2] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]

我的猜测是,虽然 t 的单独定义不会触发编译错误,但对 t 的额外“触摸”可能会。如果您让编译器推断出正确的类型,一切都会正常工作:

val t2 = new MyType[String, SubMode[String]] {}
t2: MyType[String,SubMode[String]] = $anon$1@19d53ab4

"some string" -> t2
// res1: (String, MyType[String,SubMode[String]]) = (some string,$anon$1@19d53ab4)

List(t2)
// res2: List[MyType[String,SubMode[String]]] = List($anon$1@19d53ab4)

【讨论】:

  • "在 t 上的任何额外“触摸”" 这并不容易。 trait Mode[T] trait MyType[T1, M1 &lt;: Mode[T1]] { def foo: Any } val t: MyType[_, _] = ??? t.foo 编译。
  • @Dmytro Mitin,谢谢你的例子。我已经软化了上述条款。
猜你喜欢
  • 2021-04-18
  • 1970-01-01
  • 2015-06-05
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 2021-08-26
相关资源
最近更新 更多