scala中的间接递归泛型类型定义 [英] Indirect recursive generic type definitions in scala
问题描述
pre $ $ code $>特征TT [T
但是我可以用一种天真的方法间接地做出一个
特征UU [V <:VV [UU [V]]]
特征VV [U <:UU [VV [U]]]
给我错误:
CyclicTraits.scala :23:错误:类型参数[UU [V]]不符合
特征VV的类型参数边界[U <:UU [VV [U]]]
特征UU [V< ;: VV [UU [V]]]
^
CyclicTraits.scala:25:错误:类型参数[VV [U]]不符合
trait UU的类型参数bounds [V< :VV [UU [V]]]
特性VV [U <:UU [VV [U]]]
^
间接类型参数递归应该如何正确表达?
解决方案不是递归 - 它实际上是类型参数不符合边界的问题,因为错误消息说。你的例子完美地工作,如果你使参数协变:
trait UU [+ V <:VV [UU [V]] ]
trait VV [+ U <:UU [VV [U]]]
在你的版本中(没有协变), V
是 VV [UU [V]]
的子类型,告诉我们是否 UU [V]
是 UU [VV [UU [V]]]
,所以我们得到一致性错误。如果类型参数是协变的,我们知道 V
是 VV [UU [V]]
的子类型, UU [V]
是 UU [VV [UU [V]]]
的子类型,一切正常。 / p>
Direct type recursion just works:
trait TT[T<:TT[T]]
But I can made indirect one with naive approach
trait UU[V <: VV[UU[V]]]
trait VV[U <: UU[VV[U]]]
give me error:
CyclicTraits.scala:23: error: type arguments [UU[V]] do not conform to
trait VV's type parameter bounds [U <: UU[VV[U]]]
trait UU[V <: VV[UU[V]]]
^
CyclicTraits.scala:25: error: type arguments [VV[U]] do not conform to
trait UU's type parameter bounds [V <: VV[UU[V]]]
trait VV[U <: UU[VV[U]]]
^
How should indirect type parameter recursion be expressed properly?
解决方案 The problem here isn't the recursion—it is actually a matter of the type parameters not conforming to the bounds, as the error message says. Your example works perfectly if you make the parameters covariant:
trait UU[+V <: VV[UU[V]]]
trait VV[+U <: UU[VV[U]]]
In your version (without the covariance), the fact that V
is a subtype of VV[UU[V]]
tells us nothing about whether or not UU[V]
is a subtype of UU[VV[UU[V]]]
, so we get the conformance error. If the type parameters are covariant, we know that V
being a subtype of VV[UU[V]]
entails that UU[V]
is a subtype of UU[VV[UU[V]]]
, and everything's fine.
这篇关于scala中的间接递归泛型类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!