如何在Scala中定义一个存在更高的接口类型 [英] How to define an existential higher kinded type in Scala
本文介绍了如何在Scala中定义一个存在更高的接口类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不幸的是Scalac不允许它。
欢迎使用Scala版本2.11.7(Java HotSpot™64位服务器虚拟机,Java 1.8.0_45)。
键入表达式让他们评估。
输入:help获取更多信息。
scala> :粘贴
//进入粘贴模式(ctrl-D完成)
特性H [F [_,_]]
特性T [A,B]
val h:H [T] = null
val e:H [F] forSome {type F [A,B]} = h
//正在解析粘贴模式。
< console>:13:error:type mismatch;
找到:H [T]
required:H [_ [A,B] <:Any]
注意:T <任意,但是特征H在类型F中是不变的。
您可能希望将F定义为+ F。 (SLS 4.5)
val e:H [F] forSome {type F [A,B]} = h
^
我该如何解决这个问题?
如何定义一个匹配任何 H
无论类型参数是什么?
更新:我甚至试图让Scalac推断存在类型,仍然不幸运。 b
欢迎使用Scala版本2.11.7(Java HotSpot™64位服务器虚拟机,Java 1.8.0_45)。
键入表达式让他们评估。
输入:help获取更多信息。
scala> :粘贴
//进入粘贴模式(ctrl-D完成)
特性H [F [_,_]]
特性T [A,B]
val h:H [T] = null
trait T2 [A,B]
val h2:H [T2] = null
Seq(h,h2)
//退出粘贴模式,现在解释。
< console>:17:error:type mismatch;
found:H [T]
required:H [_>:T2 with T<:Object]
Seq(h,h2)
^
< b< ; console>:17:error:type mismatch;
found:H [T2]
required:H [_>:T2 with T<:Object]
Seq(h,h2)
^
解决方案
您可以使用类型成员来代替类型参数:
特质H {
type F [_,_]
}
I was trying to define a type that accept an existential higher kinded type in Scala.
Unfortunately Scalac does not allow it.
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait H[F[_, _]]
trait T[A, B]
val h:H[T] = null
val e:H[F] forSome { type F[A, B] } = h
// Exiting paste mode, now interpreting.
<console>:13: error: type mismatch;
found : H[T]
required: H[_[A, B] <: Any]
Note: T <: Any, but trait H is invariant in type F.
You may wish to define F as +F instead. (SLS 4.5)
val e:H[F] forSome { type F[A, B] } = h
^
How could I workaround it?
How could I define a type that matches any H
whatever the type parameter is?
Update: I even tried to let Scalac infer the existential type, still not lucky.
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait H[F[_, _]]
trait T[A, B]
val h:H[T] = null
trait T2[A, B]
val h2:H[T2] = null
Seq(h, h2)
// Exiting paste mode, now interpreting.
<console>:17: error: type mismatch;
found : H[T]
required: H[_ >: T2 with T <: Object]
Seq(h, h2)
^
<console>:17: error: type mismatch;
found : H[T2]
required: H[_ >: T2 with T <: Object]
Seq(h, h2)
^
解决方案
Instead of a type parameter you could use a type member:
trait H {
type F[_, _]
}
这篇关于如何在Scala中定义一个存在更高的接口类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文