scala中的间接递归泛型类型定义 [英] Indirect recursive generic type definitions in scala

查看:104
本文介绍了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屋!

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