Eugene Yokota
Eugene Yokota

Reputation: 95604

How do I cast a variable in Scala?

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

Upvotes: 199

Views: 95090

Answers (2)

Daniel Spiewak
Daniel Spiewak

Reputation: 55115

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.

Upvotes: 283

Eugene Yokota
Eugene Yokota

Reputation: 95604

g.asInstanceOf[Graphics2D];

Upvotes: 227

Related Questions