Scala-链接两个隐式转换时如何模式匹配? [英] Scala - how to pattern match when chaining two implicit conversions?
问题描述
我编写了一种解析Metrics数据的方法,首先遇到了transactionMap类型的问题,该类型是 java.util.Map
。我使用JavaConverters解决了它。
I wrote a method to parse Metrics data and at first faced a problem with the type of transactionMap which is a java.util.Map
. And I solved it using JavaConverters.
def parseMetrics(metric: Metric) = {
import scala.collection.JavaConverters._
metric.transactionMap.asScala.values.map {
case false => "N"
case true => "Y"
}.toList
但是此后在模式匹配为真时出现错误和错误值:模式类型与预期类型不兼容,发现:布尔值,必需:java.lang.Boolean
But after that I got an error while pattern matching true and false values: pattern type is incompatible with expected type, found: Boolean, required: java.lang.Boolean
据我了解,Scala没有链接两个隐式转换。有没有办法使用JavaConverters修复它?
As far as I understand Scala does not chain two implicit conversions. Is there a way to fix it using JavaConverters?
推荐答案
使用if / else而不是match语句进行布尔检查:
Use if/else rather than a match statement for Boolean checking:
def parseMetrics(metric: Metric) = {
import scala.collection.JavaConverters._
metric.transactionMap.asScala.values.map {
x => if (x) "Y" else "N"
}.toList
我的怀疑是在if语句中,可以将 java.lang.Boolean
(我在这里假定为 x
)强制为 Boolean
通过 import scala.collection.JavaConverters ._
...但match语句不会执行相同的强制,但必须显式进行(或匹配 java.lang.Boolean
值)。
My suspicion is that within the if statement the java.lang.Boolean
(which I presume x
is here) can be coerced to Boolean
via import scala.collection.JavaConverters._
... but the match statement doesn't do the same coercion, but would have to be made explicitly (or match on the java.lang.Boolean
values).
这篇关于Scala-链接两个隐式转换时如何模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!