Given a variable with type Graphics
, I want to cast it to Graphics2D
in Scala.
views:
2658answers:
2
+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
2009-05-31 15:21:16
+1 because it's interesting, but a bit too much for this scenario. isn't it?
eed3si9n
2009-05-31 21:07:19