So let’s say you have a java method:

public Object getSomething(String key) { ... }

This returns an Object, or null. Ideally it would have a generic type so that it at least returned the type you expect (like String), rather than Object, but that’s java for you. What’s a scala chap to do with such an ugly method?

val obj = getSomething("key")
val maybeObj = obj match {
	case s:String => Some(s)
	case _ => None
val actualObj = maybeObj.getOrElse("")

Not very nice, is it? We should abstract this (unfortunately) common pattern!

My first attempt was like so:

def iWant[A](v:Object):Option[A] = {
	v match {
		case correct:A => return Some(correct)
		case _ => return None

scala> iWant[String]("foo")
res: Option[String] = Some(foo)

good so far, but …

scala> iWant[String](None)
res: Option[String] = Some(None)

scala> iWant[String](new Object())
res: Option[String] = Some(java.lang.Object@72cc5002)

Uh oh, smells like type-erasure! A few googles later, I found this page, with an example and a link to this explanation of scala reified types.

So armed with that knowledge and a concrete example, our function now becomes:

def iWant[A](v:Object)(implicit m: scala.reflect.Manifest[A]):Option[A] = {
	if (m.erasure.isInstance(v)) {
		return Some(v.asInstanceOf[A])
	} else {
		return None

scala> iWant[String](null)
res: Option[String] = None

scala> iWant[String]("thing")
res: Option[String] = Some(thing)

scala> iWant[String](new Object())
res: Option[String] = None

Tada! Now the original example is just:

val str = iWant[String](getSomething("key")).getOrElse("")

Not exactly beautiful, but not too awful either. I don’t know if something like this is in the standard library already, as I’m still pretty new to scala. But if there is, it’s still neat to learn how it would work…