如何避免使用广义类型约束的强制转换?

时间:2018-05-31 17:22:09

标签: scala types

我正在设计以下特征和方法:

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)

是否有可能消除这种演员?

1 个答案:

答案 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")
}