Michael
Michael

Reputation: 42050

How to downcast with reflection in Scala?

Suppose I have a non-sealed trait A and need a function convert[T <: A]: A => Option[T]:

def convert[T <: A](a: A): Option[T] = // don't compile
  if (a is instance of T) then Some(a) else None 

How would you suggest implement that convert ?

P.S I don't like reflection but need to deal with legacy, which uses it.

Upvotes: 0

Views: 249

Answers (1)

lmm
lmm

Reputation: 17431

Rather than isInstance, you can use the ClassTag in a match expression, which is slightly clearer:

def convert[T <: A](a: A)(implicit ct: ClassTag[T]) = a match {
  case ct(t) => Some(t)
  case _ => None
}

Upvotes: 2

Related Questions