由于foreach中的隐式转换不明确,因此无法编译

时间:2019-04-22 13:57:46

标签: scala

我当前的问题是在处理elementsecondElement变量中的字段名称时,它们恰好是BSONObject类型的对象。

val set        = element.keySet().union(secondElement.keySet())

set.foreach(key => {
            basicDbObject.put(key, getNumber(element, key) + getNumber(secondElement, key))

...

getNumber的工作方式如下...

def getNumber(element: BSONObject, field: String): Long =
    if (element.containsField(field)) element.get(field).asInstanceOf[Long] else 0

但是,每当我尝试编译并运行代码时,就会发生以下错误...

[error]  found   : Long
[error]  required: ?{def +(x$1: ? >: Long): ?}
[error] Note that implicit conversions are not applicable because they are ambiguous:
[error]  both method long2float in object Long of type (x: Long)Float
[error]  and method long2double in object Long of type (x: Long)Double
[error]  are possible conversion functions from Long to ?{def +(x$1: ? >: Long): ?}
[error]         basicDbObject.put(key, getNumber(element, key) + getNumber(secondElement, key))

除了上一个,还显示了另一个告诉我检查类型不匹配。

[error]  found   : Long
[error]  required: String
[error]         basicDbObject.put(key, getNumber(element, key) + getNumber(secondElement, key))

1 个答案:

答案 0 :(得分:0)

也许模式匹配在这里起作用:

尝试将值转换为match内的值,以防它是Long的实例。

def getNumber(element: BSONObject, field: String): Long =
    if (element.containsField(field)) 
        element.get(field) match {
           case x: Long => x
           case _ => // Default behaviour
        }
    else 0l

要了解该错误试图告诉您什么:

Note that implicit conversions are not applicable because they are ambiguous:
[error]  both method long2float in object Long of type (x: Long)Float
[error]  and method long2double in object Long of type (x: Long)Double
[error]  are possible conversion functions from Long to ?{def +(x$1: ? >: Long): ?}

getNumber(element, key) + getNumber(secondElement, key)中,您有时会返回Long,有时返回0(这是Int)。