How do I cast a variable in Scala?

Scala

Scala Problem Overview


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

Scala Solutions


Solution 1 - Scala

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.

Solution 2 - Scala

g.asInstanceOf[Graphics2D];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEugene YokotaView Question on Stackoverflow
Solution 1 - ScalaDaniel SpiewakView Answer on Stackoverflow
Solution 2 - ScalaEugene YokotaView Answer on Stackoverflow