Scala:如何抑制未经检查的警告/正确执行地图的模式匹配? [英] Scala: How to suppress unchecked warnings / do pattern matching of maps correctly?
问题描述
在测试调用中返回一个 Option[Any]
的第三方函数.我知道如果这个函数返回一个 Map
,它就是一个 Map[String, Any]
.在这种情况下,我想检查单个地图元素.
In a test call a third-party function which returns an Option[Any]
. I know if this function returns a Map
, it is a Map[String, Any]
. In this case, I want to check for individual map elements.
theFunction(...) match {
case Some(m: Map[String, Any]) =>
m("some key") match {
case some_condition => ... (my check)
}
case _ => fail("Invalid type")
}
但编译器警告 case Some(m: Map[String, Any])
未选中.当我改用 Map[_,_]
时,编译器会在我检查 m("some key")
的时候退出.
But the compiler warns that case Some(m: Map[String, Any])
is unchecked. When I use Map[_,_]
instead, the compiler bails out at the point where I check m("some key")
.
如何抑制此警告,或者更好:如何正确执行此检查?我能想到的唯一方法是
How do I suppress this warning, or better: how do I do this check correctly? The only approach I can think of is something like
theFunction(...) match {
case Some(m: Map[_,_]) =>
val m1: Map[String, Any] = m.toSeq.map(t => t._1.asInstanceOf[String] -> t._2).toMap
m1("some key") match {
case some_condition => ... (my check)
}
}
但在我看来,这看起来很丑陋,并且引入了不必要的映射到 Seq 的转换,反之亦然.
but in my eyes, this looks ugly and introduces unnecessary converting of the map to a Seq and vice-versa.
推荐答案
目前没有办法在 Scala 中抑制这些警告.此处有一些关于该主题的有趣讨论.您可以忽略警告,或使用 asInstanceOf
:
There is currently no way to suppress these warnings in Scala. There's some interesting discussion about the topic here. You can ignore the warning, or use asInstanceOf
:
m.asInstanceOf[Map[String, Any]]("some key") match { ... }
这些类型的运行时操作容易出错,并且通常指向糟糕的类型系统.在极少数情况下,方法应该返回 Option[Any]
.在 Scala 中,几乎任何使用 Any
作为返回类型都是一个危险信号.
These types of runtime operations are error prone, and usually point to a poor type system. There are very few situations in which a method should return Option[Any]
. Almost any use of Any
as a return type is a red flag in Scala.
这篇关于Scala:如何抑制未经检查的警告/正确执行地图的模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!