在Scala中创建元组时键入绑定错误 [英] Type bound error when creating a tuple in scala

查看:53
本文介绍了在Scala中创建元组时键入绑定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个类型

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

这个编译

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

但不是这个

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

错误表示类似类型参数[_$0,_$1]不符合特征MyType的类型参数边界

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

So my question is that why this does not compile on tuple creation?

推荐答案

实际上 tsome string" ->t 将在运行时因相同问题而中断:

Actually both t and "some string" -> t will break at runtime with the same issue:

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]]

事实上,编译时的问题并不是元组特有的.例如:

In fact, the issue at compile-time is not specific to Tuples. For example:

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

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

My guess is that while the definition of t alone does not trigger a compilation error, an additional "touch" on t might. It'll all work fine if you let the compiler infer the proper type:

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)

这篇关于在Scala中创建元组时键入绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆