views:

101

answers:

2
+3  Q: 

Converting Types

I was trying to convert an object with Object type into FontUIResource type. In Java, it would be

FontUIResource font = (FontUIResource)value

How would I do that in Scala?

+3  A: 

You mean casting, not Boxing and Unboxing, since that applies to primitive values. value.asInstanceOf[FountUIResource] is the way to cast this in Scala.

Arjan Blokzijl
Primitive values, rather than numeric.
Synesso
+6  A: 

You can say value.asInstanceOf[FontUIResource], or you can use a match-case block:

value match{
  case f:FontUIResource => 
    //do something with f, which is safely cast as a FontUIResource
  case _ => 
    //handle the case when it's not the desired type
}
MJP
The kind of `case` illustrated here is essentially syntactic sugar for an `isInstanceOf` / `asInstanceOf` pair with the casted value assigned to the match variable (`f` in this example). It should be clear why the `match` form is preferable to the is / as code.
Randall Schulz