I am working with trees and lists of expressions (Exp
, members removed for brevity).
sealed abstract class Exp
abstract class BinaryExp extends Exp
case class Add extends BinaryExp
Most of the time I use pattern matching to process a tree or list of expressions. But sometimes this is a bit tedious and I want to be able to write:
if (exp.isBinary) ...
//or
exps.filter(_.isAdd) ...
But this would mean that I need to create all sorts of properties in Exp
with an implementation like:
def isXXX = this.isInstanceOf[XXXExp]
My first attempt to make this generic does not work because of type erasure:
def is[T <: Exp] = this.isInstanceOf[T]
So I searched for a solution and found TypeTags:
http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
Scala: What is a TypeTag and how do I use it?
Attempt with TypeTags does not work either:
sealed abstract class Exp {
// Cannot use isInstanceOf because of type erasure.
import reflect.runtime.universe._
def is[T <: Exp: TypeTag] = typeOf[this.type] <:< typeOf[T]
def as[T <: Exp] = asInstanceOf[T]
}
Is there a way in Scala to do this?