我有以下代码
val a = (1 to 10)
a.toSet.map(i => new File(i.toString).length).sum
并且它使用Scala 2.12.4编译错误
Error:(74, 15) missing parameter type
a.toSet.map(i => new File(i.toString).length).sum
Error:(74, 49) ambiguous implicit values:
both object BigIntIsIntegral in object Numeric of type
scala.math.Numeric.BigIntIsIntegral.type
and object ShortIsIntegral in object Numeric of type
scala.math.Numeric.ShortIsIntegral.type
match expected type Numeric[B]
a.toSet.map(i => new File(i.toString).length).sum
Error:(74, 49) could not find implicit value for parameter num: Numeric[B]
a.toSet.map(i => new File(i.toString).length).sum
Error:(74, 49) not enough arguments for method sum: (implicit num: Numeric[B])B.
Unspecified value parameter num.
a.toSet.map(i => new File(i.toString).length).sum
我猜测编译器抱怨它找不到sum(implicit num: scala.Numeric[B])
的好候选人。但是,如果我只是将toSet
更改为distinct
,则错误将消失。我不太明白如何解释这一点。在这两种情况下,我都使用sum
代替sum()
。
任何人都可以帮我解释错误的根本原因吗?谢谢!
答案 0 :(得分:2)
想一想,与Missing parameter type error by calling toSet?
重复问题是toSet
通常规则是编译器应该选择最具体的值。但是由于函数在它们的参数中是逆变的,所以当它们将Any作为参数时它们是最具体的,因此编译器无法做出决定。
答案 1 :(得分:0)
除了Evgeny的答案之外,你可以像这样帮助进行类型推断:
val a = (1 to 10)
a.toSet[Int] /* ! */.map(i => new File(i.toString).length).sum
答案 2 :(得分:0)
我们需要一套吗?
a.map {i:Int => (new File (i.toString)).length()}.sum // or:
a.map {i:Int => new File (i.toString).length}.sum