Given a variable with type Graphics,
how do I cast it to Graphics2D in Scala?
2 Answers
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.
6 Comments
base match { case base @ MyConcrete(value) => base.something(value) } Obviously, shadowing base is optional. You could just as easily use a different variable name.val gResult = g match { case g2: Graphics2D => g2 case _ => throw new ClassCastException }g.asInstanceOf[Graphics2D];
5 Comments
asInstanceOf, since it defeats the purpose of having static type system and feels yucky.scala-swing components, paintComponent's parameter is already Graphics2D so no cast required