带上限的联合类型 [英] Union type with upper bound

查看:22
本文介绍了带上限的联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循这个问题的公认答案中提出的技术如何定义类型分离"(联合类型)? 以支持对方法的多类型参数进行类型检查.

I was following the technique presented in the accepted answer to this question How to define "type disjunction" (union types)? in order to support type checking for a multiple-type parameter to a method.

隐含的证据"

@implicitNotFound(msg="Only String, Array[Byte] and InputStream are supported")
  sealed class Input[T]
  object Input{
    implicit object ByteArrayWitness extends Input[Array[Byte]]
    implicit object StringWitness extends Input[String]
    implicit object InputStreamWitness extends Input[InputStream]
  }

API 方法

def foo[T: Input](param: T) =
  param match {
    case x: String => //...
    case x: Array[Byte] => //...
    case x: InputStream => //...
    case _ => throw new UnsupportedOperationException(s"not implemented for type ${param.getClass}")
  }

问题

这个编译

foo("test")
foo(Array[Byte](123.toByte))

但这不是(因为它不是一个具体的InputStream)

but this does not (because it's not a concrete InputStream)

foo(new ByteArrayInputStream("abc".getBytes("UTF-8")))

我必须将它强制转换为确切的超类型才能使其工作(编译)

I have to cast it to the exact super type to make it work (this compiles)

foo(new ByteArrayInputStream("abc".getBytes("UTF-8")).asInstanceOf[InputStream])

有没有办法改变

    implicit object InputStreamWitness extends Input[InputStream]

所以它是所有扩展 InputStream 的证据?我有一种感觉有一些上限 <: 符号可以插入某个地方,我真的不知道在哪里......

So that it is an evidence for everything that extends InputStream? I have a feeling there is some upper bound <: notation to plug in somewhere, I just really don't know where...

或者这是来自上述问题的最高投票答案的疯狂的 lambda 演算的东西"来拯救吗?

Or is this where the "crazy lambda calculus stuff" from the highest voted answer to the aforementioned question comes to the rescue?

推荐答案

Make Input contra variant in type T like: Input[-T],表示如果A是B的超类型,则Input[B]是Input[A]的超类型(反向继承").在您的情况下,它只是意味着 Input[InputStream] 知道如何处理所有子类输入类型 InputStream(如 ByteArrayInputStream)

Make Input contra variant in type T like: Input[-T], it means that if A is super type of B, then Input[B] is super type of Input[A] (reverse "inheritance"). In your case it simply means that Input[InputStream] knows how to handle all subclasses input type InputStream (like ByteArrayInputStream)

我非常喜欢 Rex Kerr 在这个问题中对逆变的解释.但是还有很多其他的

I really like the explanation on contravariance by Rex Kerr in this question. But there are many others

这篇关于带上限的联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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