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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:17:53  来源:igfitidea点击:

Explicit Type Conversion in Scala

scalatype-conversion

提问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
  }
}