我当前的问题是在处理element
和secondElement
变量中的字段名称时,它们恰好是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))
答案 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
)。