【发布时间】:2014-08-14 18:41:23
【问题描述】:
我正在遵循这个问题的公认答案中提出的技术 How to define "type disjunction" (union types)? 以支持对方法的多类型参数进行类型检查。
隐含的“证据”
@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)
foo(new ByteArrayInputStream("abc".getBytes("UTF-8")))
我必须将它转换为确切的超类型才能使其工作(编译)
foo(new ByteArrayInputStream("abc".getBytes("UTF-8")).asInstanceOf[InputStream])
有没有办法改变
implicit object InputStreamWitness extends Input[InputStream]
所以它是所有扩展InputStream的证据?我感觉有一些上限 <: 符号可以插入某个地方,我真的不知道在哪里......
或者这就是来自上述问题的最高投票答案的“疯狂的 lambda 演算东西”来拯救?
【问题讨论】: