以一种类型安全的方式合并相关的ADT

问题描述

我正在设计一种可以与“类型”一起使用的类型安全api-我正在处理的应用程序中的抽象。这是它的样子:

sealed trait EnumType

case object A extends EnumType
case object B extends EnumType
case object C extends EnumType

sealed abstract class TypeInfo[T <: EnumType](val enumType: T)

case class Ainfo() extends TypeInfo(A)
case class Binfo() extends TypeInfo(B)
case class Cinfo() extends TypeInfo(C)

sealed trait TypeMeta[T <: EnumType]

case class Ameta() extends TypeMeta[A.type]
case class Bmeta() extends TypeMeta[B.type]
case class Cmeta() extends TypeMeta[C.type]

case class TypeDescription[T <: EnumType](info: TypeInfo[T],meta: TypeMeta[T])

对于定义一个接受List中的TypeInfo并返回TypeDescription的函数,我感到困惑。我目前将其实现如下:

//Type parameter with omitted bound? Is that type safe?
def toDescription(lst: List[TypeInfo[_]]): List[TypeDescription[_]] = {
  lst map {
    case a: Ainfo => TypeDescription(a,Ameta())
    case b: Binfo => TypeDescription(b,Bmeta())
    case c: Cinfo => TypeDescription(c,Cmeta())
  }
}

要解决此问题,我使用了[_]模式,该模式看起来不太安全。有没有办法重新声明该功能?

解决方法

其类型为safe,但是2个类型参数分别绑定到它们自己的约束,而不是彼此绑定。 如果您打算这样做,我认为您需要像这样定义一个方法类型参数

  //Type parameter with omitted bound? Is that type safe?
def toDescription[T<:EnumType](lst: List[TypeInfo[T]]): List[TypeDescription[T]] = {
  lst map {
    case a: Ainfo => TypeDescription(a,Ameta())
    case b: Binfo => TypeDescription(b,Bmeta())
    case c: Cinfo => TypeDescription(c,Cmeta())
  }
}

现在,如果您想写

case a: Ainfo => TypeDescription(a,Bmeta())

您会收到编译错误

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...