Scala 中的显式类型转换 [英] Explicit Type Conversion in Scala
本文介绍了Scala 中的显式类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下代码:
abstract class Animal
case class Dog(name:String) extends Animal
var foo:Animal = Dog("rover")
var bar:Dog = foo //ERROR!
如何修复这段代码的最后一行?基本上,我只想做些什么,用类似 C 的语言就可以做到:
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
推荐答案
这是我自己想出来的.有两种解决方案:
I figured this out myself. There are two solutions:
1) 进行显式转换:
var bar:Dog = foo.asInstanceOf[Dog]
2) 使用模式匹配为您进行转换,这也会捕获错误:
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
}
}
这篇关于Scala 中的显式类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文