78

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
Frank S. Thomas
  • 4,725
  • 2
  • 28
  • 47
Kevin Albrecht
  • 6,974
  • 7
  • 44
  • 56

1 Answers1

149

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
  }
}
Kevin Albrecht
  • 6,974
  • 7
  • 44
  • 56
  • 14
    Note, that second way is error-prone on generics due to JVM type erasure – om-nom-nom Apr 08 '12 at 21:19
  • @om-nom-nom may you explain it a little bit? thanks. – Weihong Diao Feb 06 '14 at 07:45
  • @WeihongDiao please, see https://stackoverflow.com/questions/1094173/how-do-i-get-around-type-erasure-on-scala-or-why-cant-i-get-the-type-paramete – om-nom-nom Feb 06 '14 at 23:40
  • @om-nom-nom: Would it be valid to combine 1) and 2) to `var bar:Dog = foo match { case x:Dog => foo.asInstanceOf[Dog] case _ => { // Error handling code here } }` ? – Make42 Oct 14 '16 at 17:53
  • @Make42 you don't need to make cast, just use `x` from pattern matching – om-nom-nom Oct 15 '16 at 18:25
  • @om-nom-nom: You said that the pattern matching is not error-prone - I thought the cast might be, or did I get that wrong? Thus I thought combining the two might eliminate all error-prone-ness? – Make42 Oct 17 '16 at 17:16
  • @Make42 checkout https://stackoverflow.com/questions/16056645/how-to-pattern-match-on-generic-type-in-scala and https://stackoverflow.com/questions/32246734/scala-pattern-match-a-function-how-to-get-around-type-erasure to get a sense of kind of problems you can have – om-nom-nom Oct 17 '16 at 18:26