How do I cast a variable in Scala?
Asked Answered
Q

2

199

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

Queeniequeenly answered 31/5, 2009 at 6:26 Comment(0)
M
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.

Macrae answered 31/5, 2009 at 15:21 Comment(6)
+1 because it's interesting, but a bit too much for this scenario. isn't it?Queeniequeenly
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)" ?Polyethylene
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.Macrae
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?Embarkment
@JamesMcMahon val gResult = g match { case g2: Graphics2D => g2 case _ => throw new ClassCastException }Confection
Why for casting only, they make it this complicated when in Java it is very easy?Frechette
Q
227
g.asInstanceOf[Graphics2D];
Queeniequeenly answered 31/5, 2009 at 6:26 Comment(5)
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.Queeniequeenly
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!Stopple
@Stopple 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 requiredBrainwashing
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?Frechette
@LemuelAdane The fact that you're using casts at all is a code smell, it makes no sense to make them easier.Sierrasiesser

© 2022 - 2024 — McMap. All rights reserved.