简体   繁体   English

Scala:在参数通配符上调用方法/访问值

[英]Scala: Calling method/accessing value on argument wildcard

How do I call a method on or access a value of an argument wildcard? 如何在通配符上调用方法或访问通配符的值? Eg in this example I want to find the max "rev" value of all F objects. 例如,在此示例中,我想找到所有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)}
                                    ^

You can't use wildcards here and need to give names to the arguments: 您不能在此处使用通配符,而需要为参数指定名称:

res3.foldLeft(0L){(x,y) => math.max(x,y.rev)}

Note that it would be the same if you had a function foo taking 1 argument instead of math.max : foo(_.rev) is the same as foo(x => x.rev) and not x => foo(x.rev) . 请注意,如果您有一个函数foo接受1个参数而不是math.max ,它将是相同的: foo(_.rev)foo(x => x.rev)相同,而不是x => foo(x.rev)

The problem is the scope of wildcards. 问题是通配符的范围。 math.max(_,_.rev) expands to (I think) x => math.max(x, y => y.rev) . math.max(_,_.rev)扩展为(我认为) x => math.max(x, y => y.rev) Since this function only has one parameter, you get this error. 由于此函数只有一个参数,因此会出现此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM