asinstanceof

How to use the Spring Framework in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 17.4, “How to use the Spring Framework in Scala.”

Problem

You want to use the Java Spring Framework library in your Scala application.

Solution

In my experience, the only real changes in using the Spring Framework in Scala applications involve how you cast the objects you instantiate from your Spring application context file, and that’s only because the casting process is different between Scala and Java.

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:

Scala “object” examples

This article is a collection of Scala “object” examples. I put the word object in quotes there because it has at least two meanings in Scala. In the first meaning, just like Java, an object is an instance of a class.

In its second meaning, Scala has an object keyword, and using that keyword lets you do a variety of things, including creating a main method to launch your application, to create the equivalent of Java’s static methods, and also to create something called a companion 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: