Given a variable with type Graphics,
how do I cast it to Graphics2D in Scala?
Given a variable with type Graphics , how do I cast it to Graphics2D
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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 returnnull(or preferably,None), or you could enter some fallback branch which works withoutGraphics2D.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.