在None子句中从Option[T]中提取类



假设您有以下代码

  trait T {
  }
  case class First(int:Int) extends T
  case class Second(int:Int) extends T
  val a:Option[T] = Option(First(3))
  val b:Option[Second] = None
  def test[A](a:Option[A])(implicit manifest:Manifest[Option[A]]) = {
    a match {
      case Some(z) => println("we have a value here")
      case None => a match {
        case t:Option[First] => println("instance of first class")
        case s:Option[Second] => println("instance of second class")
      }
    }
  }
  test(b)

如果选项恰好为None,您将如何提取封闭Atype。我尝试过各种组合的清单,但他们似乎都没有工作,每次它抱怨类型被消除与擦除,即

non-variable type argument First in type pattern Option[First] is unchecked since it is eliminated by erasure

您可以使用type标签,这是Manifest的现代替代品:

import scala.reflect.runtime.universe._
trait T
case class First(int:Int) extends T
case class Second(int:Int) extends T
def test[A: TypeTag](a: Option[A]) = {
  a match {
    case Some(_) => println("we have a value here")
    case None => typeOf[A] match {
      case t if t =:= typeOf[First] => println("instance of First")
      case t if t =:= typeOf[Second] => println("instance of Second")
      case t => println(s"unexpected type $t")
    }
  }
}

例子
val a = Option(First(3)) // we have a value here
val b: Option[First] = None // instance of First
val c: Option[Second] = None // instance of Second
val d: Option[Int] = None // unexpected type Int

顺便说一下,您对A的类型感兴趣(通过擦除消除),因此即使有清单,您也需要A上的清单,而不是Option[A]上的清单。

相关内容

  • 没有找到相关文章

最新更新