Scala 中的显式类型转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/171489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explicit Type Conversion in Scala
提问by Kevin Albrecht
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:
如何修复此代码的最后一行?基本上,我只想做些什么,用类 C 语言就可以做到:
var bar:Dog = (Dog) foo
回答by Kevin Albrecht
I figured this out myself. There are two solutions:
这是我自己想出来的。有两种解决方案:
1) Do the explicit cast:
1) 进行显式转换:
var bar:Dog = foo.asInstanceOf[Dog]
2) Use pattern matching to cast it for you, this also catches errors:
2)使用模式匹配来为你投射,这也会捕获错误:
var bar:Dog = foo match {
case x:Dog => x
case _ => {
// Error handling code here
}
}

