How Can I Check an Object to See its Type and Return A Casted Object

Russ Bradberry picture Russ Bradberry · Apr 17, 2010 · Viewed 28.3k times · Source

I have method to which I pass an object. In this method I check it's type and depending on the type I do something with it and return a Long. I have tried every which way I can think of to do this and I always get several compiler errors telling me it expects a certain object but gets another. Can someone please explain to me what I am doing wrong and guide me in the right direction? What I have tried thus far is below:

  override def getInteger(obj:Object) = {
    if (obj.isInstanceOf[Object]) null
    else if (obj.isInstanceOf[Number]) 
      (obj:Number).longValue()
    else if (obj.isInstanceOf[Boolean]) 
      if (obj:Boolean) 1 else 0
    else if (obj.isInstanceOf[String]) 
      if ((obj:String).length == 0 | (obj:String) == "null") 
        null
      else
          try {
            Long.parse(obj:String)
          } catch {
            case e: Exception => throw new ValueConverterException("value \"" + obj.toString() + "\" of type " + obj.getClass().getName() + " is not convertible to Long")        
          }
  }

Answer

missingfaktor picture missingfaktor · Apr 17, 2010

Pattern matching would make it much more nicer.

def getInteger(obj: Any) = obj match {
  case n: Number => n.longValue
  case b: Boolean => if(b) 1 else 0
  case s: String if s.length != 0 && s != "null" => s.toLong
  case _ => null
}