199

Given a variable with type Graphics, how do I cast it to Graphics2D in Scala?

2 Answers 2

283

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.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 because it's interesting, but a bit too much for this scenario. isn't it?
what if I already patternmatched but lost reference to the casted value: <code>base match { case MyConcrete(value) => base.asInstanceOf[MyConcrete].something(value) } </code>, is there a way to get 'base' casted to MyConcrete even if want to extract "value" by exploiting the 'unapply' call performed by "case MyConcrete(value)" ?
Try this: base match { case base @ MyConcrete(value) => base.something(value) } Obviously, shadowing base is optional. You could just as easily use a different variable name.
What I don't get is how would you get the result of this pattern matching cast into a variable? like in java if it was String a = (String) b; what would the scala equivalent be?
@JamesMcMahon val gResult = g match { case g2: Graphics2D => g2 case _ => throw new ClassCastException }
|
227
g.asInstanceOf[Graphics2D];

5 Comments

Once I got used to Scala, I learnt not to use asInstanceOf, since it defeats the purpose of having static type system and feels yucky.
Unfortunately, this a common operation when using Swing. For custom painting operations, you need to override the 'public void paintComponent(Graphics g)' method. The Graphics parameter is actually a Graphics2D instance, but a cast is needed. The pattern matching version is probably more verbosity than warranted. Remember: Sedulously eschew obfuscatory hyperverbosity and prolixity!
@hohonuuli I think the cast is fine in that specific case, but if you use scala-swing components, paintComponent's parameter is already Graphics2D so no cast required
Why its so long? Why "asInstanceOf when can be only be "as" or "asof" keyword or method? Or why they did not just adopt the C++ and Java way as an option because that is the conventional and there is no big problem with that?
@LemuelAdane The fact that you're using casts at all is a code smell, it makes no sense to make them easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.