0

Assuming you have the following code

  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)

How would you extract what type the enclosing A is if the option happens to be a None. I have attempted to do various combinations of manifests, but none of them seem to work, each time it complains about the types being eliminated with erasure, i.e.

non-variable type argument First in type pattern Option[First] is unchecked since it is eliminated by erasure
mdedetrich
  • 1,899
  • 1
  • 18
  • 29
  • Have you tried `Manifest[A]` (or tag equivalent) instead of the current implicit argument? So that you could use this meta data about `A` type. – cchantep Aug 19 '14 at 09:28

1 Answers1

2

You can use a type tag, a modern replacement for 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")
    }
  }
}

Example

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

By the way, you are interested in the type of A (which is being eliminated by erasure), so even with manifests you need one on A and not on Option[A].

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235