Scala中的显式类型转换


76

可以说我有以下代码:

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

如何修复此代码的最后一行?基本上,我只想做类似C语言的事情:

var bar:Dog = (Dog) foo

Answers:


142

我自己弄清楚了。有两种解决方案:

1)执行显式转换:

var bar:Dog = foo.asInstanceOf[Dog]

2)使用模式匹配为您强制转换,这还会捕获错误:

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

14
请注意,由于JVM类型擦除,第二种方法在泛型上容易出错
om-nom-nom

@ om-nom-nom您可以解释一下吗?谢谢。
刁伟宏


@ om-nom-nom:将1)和2)组合为有效var bar:Dog = foo match { case x:Dog => foo.asInstanceOf[Dog] case _ => { // Error handling code here } }吗?
Make42 '16

@ Make42您不需要进行强制转换,只需x从模式匹配中使用
om-nom-nom
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.