gpt4 book ai didi

Scala:如何抑制未经检查的警告/正确进行 map 的模式匹配?

转载 作者:行者123 更新时间:2023-12-03 02:10:06 24 4
gpt4 key购买 nike

在测试中调用返回Option[Any]的第三方函数。我知道如果这个函数返回一个Map,它就是一个Map[String, Any]。在本例中,我想检查各个 map 元素。

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") 时退出。

如何抑制此警告,或者更好:如何正确执行此检查?我能想到的唯一方法是这样的

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 的转换,反之亦然。

最佳答案

您可以使用unchecked注释来抑制此类编译器警告(对于非详尽的匹配和由于类型删除而导致的无果匹配)。

来自 scaladoc:

An annotation to designate that the annotated entity should not be considered for additional compiler checks. Specific applications include annotating the subject of a match expression to suppress exhaustiveness warnings, and annotating a type argument in a match case to suppress unchecked warnings.

Such suppression should be used with caution, without which one may encounter scala.MatchError or java.lang.ClassCastException at runtime. In most cases one can and should address the warning instead of suppressing it.

示例:

val m: Any = Some(Map("a" -> 1, "b" -> "b"))
m match {
case Some(m: Map[String, Any]) => println("map")
case None => println("None")
}

<console>:30: warning: non-variable type argument String in type pattern scala.collection.immutable.Map[String,Any] (the underlying of Map[String,Any]) is unchecked since it is eliminated by erasure
case Some(m: Map[String, Any]) => println("map")

我们可以在匹配中的 Map[String, Any] 中添加 @unchecked 注释:

m match {
case Some(m: Map[String, Any] @unchecked) => println("I'm a map!")
case None => println("None")
}

// Exiting paste mode, now interpreting.

I'm a map!

不再有警告。但这显然并不比允许警告更安全,并且可能会导致一些令人惊讶的匹配错误或 ClassCastException

关于Scala:如何抑制未经检查的警告/正确进行 map 的模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29969300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com