[英]How to define an existential higher kinded type in Scala
我试图定义一个在Scala中接受存在性更高的kinded类型的类型。
不幸的是,Scalac不允许这样做。
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
^
我怎么能解决它?
无论类型参数是什么,我如何定义匹配任何H
的类型?
更新:我甚至试图让Scalac推断出存在主义类型,但仍然不幸运。
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)
^
可能sschaef是对的,这是不可能的。 我不知道以下内容是否对您有所帮助:
type F[A,B] = X[A,B] forSome { type X[A,B] } // alias
trait H[F[_, _]]
trait T[A, B]
val h: H[T] = null
val e: H[F] = h.asInstanceOf[H[F]]
我发现存在性较高的类型可以用类型模式编写(并从那里推断):
def toExistential[F[_, _]](h: H[F]) = h.asInstanceOf[Any] match {
case x: H[_] => x
}
> val h = new H[T] {}
h: H[T] = $anon$1@4d0c3eac
> val f = toExistential(h)
f: H[_] = $anon$1@4d0c3eac
对Any
的强制转换似乎是必要的,但至少它可以封装在一个函数中。
您可以使用类型成员而不是类型参数:
trait H {
type F[_, _]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.