How to cast a null value in Java alvin February 4, 2016 - 2:12pm

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) alvin June 14, 2015 - 12:40pm

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).”


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


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 convert between numeric types in Scala

Scala FAQ: How do I convert between numeric types in Scala, such as from Int to Long, Int to Double, etc.?


Instead of using the “cast” approach in Java, use the to* methods that are available on all of Scala’s numeric types. These methods can be demonstrated in the REPL (note that you need to hit the [Tab] key at the end of the first example):

Scala: How to convert a String to an Int (Integer)

Scala FAQ: How do I convert a String to Int in Scala?

Solution: Use 'toInt()'

If you need to convert a String to an Int in Scala, just use the toInt method, which is available on String objects, like this:

Class casting in Scala alvin January 24, 2012 - 10:13am

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:

How do I convert a String to a double with Java?

Question: How do I convert a String to a double with Java?

Answer: Converting a String to a double requires that you first convert the String to a Double object, then convert the Double object to a double data type (Double is an object, while double is a primitive data type).

Here's the source code for an example Java program that performs this conversion: