加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Scala“match”语句中匹配课程?

发布时间:2020-12-16 09:30:58 所属栏目:安全 来源:网络整理
导读:我如何使用“match”语句来标识一个类变量的值?以下是无效的,我找不到可接受的变体 – 除了… else if … else … val c: Class[_] = classOf[Int]val what = c match { case classOf[Int] = "int!"; case classOf[Float] = "float!" } 编译器抱怨:error
我如何使用“match”语句来标识一个类变量的值?以下是无效的,我找不到可接受的变体 – 除了… else if … else …

val c: Class[_] = classOf[Int]
val what = c match { case classOf[Int] => "int!"; case classOf[Float] => "float!" }

编译器抱怨:error:not found:type classOf

当然,我不能使用Class [Int],因为类型信息被删除:

c match { case Class[Int] => "int!"; case Class[Float] => "float!" }
error: type Class of type Class does not take type parameters.

我也尝试过像Int.class这样的变体,一切都无济于事。 (我真的不想转换成字符串:我觉得编译器catch重命名/移动类是很重要的。)

我是密集的,还是偶然发现了Scala盲点?

解决方法

如果您为他们创建一个稳定的标识符(即一个val),您可以匹配类值,

scala> val c: Class[_] = classOf[Int]
c: Class[_] = int

scala> val ClassOfInt = classOf[Int]
ClassOfInt: java.lang.Class[Int] = int

scala> val ClassOfFloat = classOf[Float]
ClassOfFloat: java.lang.Class[Float] = float

scala> val what = c match {
     |     case ClassOfInt => "int!"
     |     case ClassOfFloat => "float!"
     | }
what: String = int!

请注意,您不能匹配类型(即Class [Int]),因为擦除意味着Class [T]的不同类型的实例化在运行时无法区分,因此下面的警告

scala> val what = c match {
     |     case _: Class[Int] => "int!"
     |     case _: Class[Float] => "float!"
     | }
warning: there were 2 unchecked warnings; re-run with -unchecked for details
what: java.lang.String = int!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读