我使用TypeTag
s并注意到非常奇怪的scala编译器行为
import scala.reflect.runtime.universe.TypeTag
def accept[T](arg : TypeTag[T]) = true
def pass[T](arg : TypeTag[T]) : TypeTag[T] = arg
val ntt = implicitly[TypeTag[Nothing]]
accept(ntt)
pass(ntt)
返回错误:
NastyNothing.scala:12: error: type mismatch;
found : reflect.runtime.universe.TypeTag[Nothing]
required: reflect.runtime.universe.TypeTag[T]
Note: Nothing <: T, but trait TypeTag is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: T`. (SLS 3.2.10)
pass(ntt)
^
我可以接受TypeTag
的{{1}}但无法传递它。此外,它与Nothing
类型参数化的任何对象类似。
Nothing
返回相同的错误:
final case class Hold[T]()
def accept[T](arg : Hold[T]) = true
def pass[T](arg : Hold[T]) : Hold[T] = arg
val hn = Hold[Nothing]()
accept(hn)
pass(hn)
处理NastyNothing.scala:24: error: type mismatch;
found : TestHolder.Hold[Nothing]
required: TestHolder.Hold[T]
Note: Nothing <: T, but class Hold is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
pass(hn)
^
- 参数化对象的正确方法是什么?如何重新定义Nothing
方法以正确处理pass
?