我正在设计以下特征和方法:
trait Reader[T]{
def read(): T
}
def rd[T, A](r: Reader[T])(implicit ev: T =:= Option[A]): Either[String, A] = r.read() match {
case Some(a) => Right(a) // <---- compile error here
case None => Left("End reached")
}
问题是我在上面的代码中遇到了编译错误:
Error:(17, 27) type mismatch;
found : a.type (with underlying type Any)
required: A
case Some(a) => Right(a)
但是当我明确地添加类型时,它会编译一个警告:
trait Reader[T]{
def read(): T
}
def rd[T, A](r: Reader[T])(implicit ev: T =:= Option[A]): Either[String, A] = r.read() match {
case Some(a: A) => Right(a) // <--- Warning here
case None => Left("End reached")
}
警告:
Warning:(17, 18) abstract type pattern A is unchecked since it is eliminated by erasure
case Some(a: A) => Right(a)
是否有可能消除这种演员?
答案 0 :(得分:5)
=:=
类实际上有一个apply
方法,可以安全地从第一个类型参数转换为第二个类型参数。所以这有效:
def rd[T, A](r: Reader[T])(implicit ev: T =:= Option[A]): Either[String, A] = ev(r.read()) match {
case Some(a) => Right(a)
case None => Left("End reached")
}