00.scala2014. 3. 28. 13:03
반응형

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:

val recognizer = cm.lookup("recognizer").asInstanceOf[Recognizer]

As you can see, I've used the Scala asInstanceOf function to cast the object I'm retrieving to a Recognizer, just like I did in the Java code.

A better way?

I should warn you that I don't think this is the Scala-preferred way of class casting. I think the approved/preferred way uses pattern matching, but since I don't understand the advantages of that approach yet, and it's also more complicated, I use this asInstanceOf casting approach.

More context

If it helps to see where this example comes from, I'm using Scala with the Java Spring Framework in one of my applications, and as you can see with a little more source code here, I'm retrieving a Recognizer and Microphone from my Spring application context file:

val cm = new ConfigurationManager("sarah.config.xml")
val recognizer = cm.lookup("recognizer").asInstanceOf[Recognizer]
val microphone = cm.lookup("microphone").asInstanceOf[Microphone]

If you're familiar with Spring, you know that both of those objects need to be cast to the correct object types when they are retrieved from the application context file.

Again, this is how I do class casting in Scala, but there is another (preferred) way to do this ... I might write about that some time ... but this is my preferred approach.

Posted by 1010