如何在 Scala 中转换变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/931463/
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
How do I cast a variable in Scala?
提问by Eugene Yokota
Given a variable with type Graphics,
how do I cast it to Graphics2Din Scala?
给定一个 type 变量,Graphics我如何将它转换Graphics2D为 Scala ?
回答by Daniel Spiewak
The preferred technique is to use pattern matching. This allows you to gracefully handle the case that the value in question is notof the given type:
首选技术是使用模式匹配。这允许您优雅地处理所讨论的值不是给定类型的情况:
g match {
case g2: Graphics2D => g2
case _ => throw new ClassCastException
}
This block replicates the semantics of the asInstanceOf[Graphics2D]method, but with greater flexibility. For example, you could provide different branches for various types, effectively performing multiple conditional casts at the same time. Finally, you don't reallyneed to throw an exception in the catch-all area, you could also return null(or preferably, None), or you could enter some fallback branch which works without Graphics2D.
该块复制了该asInstanceOf[Graphics2D]方法的语义,但具有更大的灵活性。例如,您可以为各种类型提供不同的分支,同时有效地执行多个条件转换。最后,你真的不需要在包罗万象的区域抛出异常,你也可以返回null(或者最好是None),或者你可以进入一些没有Graphics2D.
In short, this is really the way to go. It's a little more syntactically bulky than asInstanceOf, but the added flexibility is almost always worth it.
简而言之,这确实是要走的路。它在语法上比 更笨重asInstanceOf,但增加的灵活性几乎总是值得的。
回答by Eugene Yokota
g.asInstanceOf[Graphics2D];

