在 scala 中创建元组时出现类型绑定错误
Type bound error when creating a tuple in scala
假设我有一个类型
trait Mode[T]
trait MyType[T, M <: Mode[T]]
这样编译
val t: MyType[_, _] = ???
t
但不是这个
val t: MyType[_, _] = ???
"some_string" -> t
错误说 type arguments [_[=13=],_] do not conform to trait MyType's type parameter bounds
所以我的问题是为什么这不能在创建元组时编译?
实际上 t
和 "some string" -> 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@596afb2f
"some string" -> t
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
reify(t)
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
reify("some string" -> t)
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
事实上,编译时的问题并不是元组特有的。例如:
List(t)
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
我的猜测是,虽然单独定义 t
不会触发编译错误,但 t
上的附加 "touch" 可能会触发编译错误。如果让编译器推断正确的类型,一切都会正常工作:
val t2 = new MyType[String, SubMode[String]] {}
t2: MyType[String,SubMode[String]] = $anon@19d53ab4
"some string" -> t2
// res1: (String, MyType[String,SubMode[String]]) = (some string,$anon@19d53ab4)
List(t2)
// res2: List[MyType[String,SubMode[String]]] = List($anon@19d53ab4)
假设我有一个类型
trait Mode[T]
trait MyType[T, M <: Mode[T]]
这样编译
val t: MyType[_, _] = ???
t
但不是这个
val t: MyType[_, _] = ???
"some_string" -> t
错误说 type arguments [_[=13=],_] do not conform to trait MyType's type parameter bounds
所以我的问题是为什么这不能在创建元组时编译?
实际上 t
和 "some string" -> 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@596afb2f
"some string" -> t
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
reify(t)
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
reify("some string" -> t)
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
事实上,编译时的问题并不是元组特有的。例如:
List(t)
// error: type arguments [_,_] do not conform to trait MyType's type parameter bounds [T,M <: Mode[T]]
我的猜测是,虽然单独定义 t
不会触发编译错误,但 t
上的附加 "touch" 可能会触发编译错误。如果让编译器推断正确的类型,一切都会正常工作:
val t2 = new MyType[String, SubMode[String]] {}
t2: MyType[String,SubMode[String]] = $anon@19d53ab4
"some string" -> t2
// res1: (String, MyType[String,SubMode[String]]) = (some string,$anon@19d53ab4)
List(t2)
// res2: List[MyType[String,SubMode[String]]] = List($anon@19d53ab4)