本文介绍了如何在 Scala 中转换变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个类型为 Graphics 的变量,如何在 Scala 中将其转换为 Graphics2D?

Given a variable with type Graphics,how do I cast it to Graphics2D in Scala?

推荐答案

首选技术是使用模式匹配.这允许您优雅地处理所讨论的值不是给定类型的情况:

The preferred technique is to use pattern matching. This allows you to gracefully handle the case that the value in question is not of the given type:

g match {
  case g2: Graphics2D => g2
  case _ => throw new ClassCastException
}

此块复制了 asInstanceOf[Graphics2D] 方法的语义,但具有更大的灵活性.例如,您可以为各种类型提供不同的分支,同时有效地执行多个条件转换.最后,您不需要真的在 catch-all 区域抛出异常,您也可以返回 null(或者最好是 None),或者您可以输入一些无需 Graphics2D 即可工作的后备分支.

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 really need 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 稍微笨重一些,但增加的灵活性几乎总是值得的.

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.

这篇关于如何在 Scala 中转换变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 07:50