简体   繁体   中英

Scala type check / assertion as a function vs JVM type erasure

I have some code that routinely does type checks like that:

obj match {
  case _: Foo =>
    // everything is fine
  case _ =>
    throw SomeException(...)
}

It works, but this is relatively bulky and feels like tons of duplicated code (especially given that exception requires lots of parameters), so I thought it would replace this an assertion function. However, my naïve try failed:

def assertType[T](obj: CommonType): Unit = {
  obj match {
    case _: T =>
      // everything is fine
    case _ =>
      throw SomeException(...)
  }
}

Obviously, due to JVM type erasure, this T parameter is ignored, so first case branch is always true. ⇒ Full source code demonstrating the problem

Of course, one can resort to Java's reflection methods, but that's slow, ugly, and unportable. What is the preferred way to do such assertions in Scala?

Somewhat related, but do not address this exact issue:

Pass the manifest as well:

def assertType[T : Manifest](obj: CommonType): Boolean

Your example code will then work correctly:

v1 is Foo = true
v1 is Bar = false
v2 is Foo = false
v2 is Bar = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM