繁体   English   中英

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

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

如何在通配符上调用方法或访问通配符的值? 例如,在此示例中,我想找到所有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) 由于此函数只有一个参数,因此会出现此错误。

暂无
暂无

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

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