scala - 在 scala 中创建元组时类型绑定错误
问题描述
说我有一个类型
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
所以我的问题是为什么这不能在创建元组时编译?
解决方案
实际上两者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$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)
推荐阅读
- python - 如何在python中创建一个循环遍历字符串列表的函数
- node.js - 错误处理与庆祝不能正常工作
- json - json和请求的Dask内存泄漏问题
- python - 如何匹配字符串中的所有数字标记?
- python - pyarrow 在大型数据集上加速 toPandas() 无效
- node.js - node.js 中的 pm2 抛出错误 Cannot find module for require dotenv from command line
- gem5 - tick()函数在gem5中的作用是什么?
- c# - 如何设置 Microsoft Graph Onlinemeeting API 设置,例如 AdditionalData 即 autoAdmittedUsers、restrictAnonymousUserJoining 等
- python - 基于条件的列中的 Fillna()
- python - 如何使用 python 从标准输入提示符读取很长的行?