_ 在 Scala lambda 函数中的使用 [英] Usage of _ in scala lambda functions

查看:42
本文介绍了_ 在 Scala lambda 函数中的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下我为什么可以这样做:

Can anyone please explain me why I can do:

a.mapValues(_.size)

代替

a.mapValues(x => x.size)

但我做不到

a.groupBy(_)

而不是

a.groupBy(x => x)

推荐答案

在这里看到它并不容易:

It isn't easy to see it here:

a.groupBy(_)

但在这样的情况下更容易看到它:

But it's easier to see it in something like this:

a.mkString("<", _, ">")

我正在部分应用该方法/功能.我将它应用于一些参数(第一个和最后一个),而不应用第二个参数,所以我得到了一个这样的新函数:

I'm partially applying the method/function. I'm applying it to some parameters (the first and last), and leaving the second parameter unapplied, so I'm getting a new function like this:

x => a.mkString("<", x, ">")

第一个示例只是部分应用唯一参数的特殊情况.但是,当您在表达式上使用下划线时,它代表匿名函数中的位置参数.

The first example is just a special case where the sole parameter is partially applied. When you use underscore on an expression, however, it stands for positional parameters in an anonymous function.

a.mapValues(_.size)
a.mapValues(x => x.size)

很容易混淆,因为它们都导致匿名函数.其实还有第三个下划线是用来把方法转换成方法值的(也是匿名函数),比如:

It is easy to get confused, because they both result in an anonymous function. In fact, there's a third underscore that is used to convert a method into a method value (which is also an anonymous function), such as:

a.groupBy _

这篇关于_ 在 Scala lambda 函数中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆