Explicit Type Conversion in Scala

ScalaType Conversion

Scala Problem Overview


Lets say I have the following code:

abstract class Animal
case class Dog(name:String) extends Animal
var foo:Animal = Dog("rover")
var bar:Dog = foo //ERROR!

How do I fix the last line of this code? Basically, I just want to do what, in a C-like language would be done:

var bar:Dog = (Dog) foo

Scala Solutions


Solution 1 - Scala

I figured this out myself. There are two solutions:

  1. Do the explicit cast:

    var bar:Dog = foo.asInstanceOf[Dog]

  2. Use pattern matching to cast it for you, this also catches errors:

    var bar:Dog = foo match { case x:Dog => x case _ => { // Error handling code here } }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin AlbrechtView Question on Stackoverflow
Solution 1 - ScalaKevin AlbrechtView Answer on Stackoverflow