casting

How to cast a null value in Java

Until a little while ago I don’t think I had ever thought about intentionally casting a null value in Java, but then I ran into a problem and realized that the solution was to cast a null value, like this:

FileDialog d = new FileDialog((java.awt.Frame) null);

You have to do that in this case because FileDialog has several one-argument constructors, including one that takes a JFrame and another that takes a JDialog. If you just put null in the constructor the Java compiler or your favorite IDE will complain, so you have to cast the null value to one of those specific types, and this syntax shows how to do this. (My app uses multiple frames, and at the moment I’d rather put null in the FileDialog constructor than try to determine which frame is currently in the foreground.)

How to cast a Scala object from one type to another (object casting)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 6.1, “How to cast an object from one type to another (object casting).”

Problem

You need to cast an instance of a class from one type to another, such as when creating objects dynamically.

Solution

Use the asInstanceOf method to cast an instance to the desired type. In the following example, the object returned by the lookup method is cast to an instance of a class named Recognizer:

How to use a Scala match expression instead of isInstanceOf (to match types)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 3.14, “How to use a match expression instead of isInstanceOf (to match types).”

Problem

In Scala, you want to write a block of code to match one type, or multiple different types.

Solution

You can use the isInstanceOf method to test the type of an object:

Class casting in Scala

While this may not be the recommended approach, here's how I currently handle class casting in Scala.

In Java you can cast a class like this:

Recognizer recognizer = (Recognizer)cm.lookup("recognizer").asInstanceOf;

As you can see, this is done with the "(Recognizer)" class cast operator.

In Scala you can't use the same syntax, but you can come close, like this: