6.1. 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:
valrecognizer=cm.lookup("recognizer").asInstanceOf[Recognizer]
This Scala code is equivalent to the following Java code:
Recognizerrecognizer=(Recognizer)cm.lookup("recognizer");
The asInstanceOf method is
defined in the Scala Any class and is
therefore available on all objects.
Discussion
In dynamic programming, it’s often necessary to cast from one type to another. This approach is needed when using the Spring Framework and instantiating beans from an application context file:
// open/read the application context filevalctx=newClassPathXmlApplicationContext("applicationContext.xml")// instantiate our dog and cat objects from the application contextvaldog=ctx.getBean("dog").asInstanceOf[Animal]valcat=ctx.getBean("cat").asInstanceOf[Animal]
It’s used when reading a YAML configuration file:
valyaml=newYaml(newConstructor(classOf[EmailAccount]))valemailAccount=yaml.load(text).asInstanceOf[EmailAccount]
The example shown in the Solution comes from code I wrote to work with an open source Java speech recognition library named Sphinx-4. With this library, many properties are defined in an XML file, and then you create recognizer and microphone ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access