如何调用方法或访问参数通配符的值? 例如,在这个例子中,我想找到所有 F 对象的最大"rev"值。
scala> case class F(rev:Long)
defined class F
scala> List(F(1),F(2),F(3))
res3: List[F] = List(F(1), F(2), F(3))
scala> res3.foldLeft(0L){math.max(_,_.rev)}
<console>:11: error: wrong number of parameters; expected = 2
res3.foldLeft(0L){math.max(_,_.rev)}
^
您不能在此处使用通配符,并且需要为参数命名:
res3.foldLeft(0L){(x,y) => math.max(x,y.rev)}
请注意,如果您有一个函数foo
取 1 个参数而不是 math.max
:foo(_.rev)
与 foo(x => x.rev)
相同而不是 x => foo(x.rev)
相同。
问题在于通配符的范围。 math.max(_,_.rev)
扩展到(我认为)x => math.max(x, y => y.rev)
.由于此函数只有一个参数,因此会出现此错误。