tags:

views:

2658

answers:

2

Given a variable with type Graphics, I want to cast it to Graphics2D in Scala.

+16  A: 
g.asInstanceOf[Graphics2D];
eed3si9n
+23  A: 

The preferred technique is to use pattern matching. This allows you to gracefully handle the case that the value in question is not of the given type:

g match {
  case g2: Graphics2D => g2
  case _ => throw new ClassCastException
}

This block replicates the semantics of the asInstanceOf[Graphics2D] method, but with greater flexibility. For example, you could provide different branches for various types, effectively performing multiple conditional casts at the same time. Finally, you don't really need to throw an exception in the catch-all area, you could also return null (or preferably, None), or you could enter some fallback branch which works without Graphics2D.

In short, this is really the way to go. It's a little more syntactically bulky than asInstanceOf, but the added flexibility is almost always worth it.

Daniel Spiewak
+1 because it's interesting, but a bit too much for this scenario. isn't it?
eed3si9n