_._1 和 __++_ 在 Scala 中是什么意思(两个单独的操作)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13045988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:39:42  来源:igfitidea点击:

What do _._1 and _++_ mean in Scala (two separate operations)?

scala

提问by user701254

My interpretation of _._1is:

我的解读_._1是:

_= wildcard parameter _1= first parameter in method parameter list But when used together with .what does it signify?

_= 通配符参数 _1= 方法参数列表中的第一个参数 但是当与.它一起使用时它意味着什么?

This is how its used :

这是它的使用方式:

.toList.sortWith(_._1 < _._1)

For this statement:

对于此声明:

_++_

I'm lost. Is it concatenation two wildcard parameters somehow? This is how its used:

我迷路了。它是以某种方式连接两个通配符参数吗?这是它的使用方式:

.reduce(_++_)

I would be particularly interested if they above code could be made more verbose and remove any implicits, just so I can understand it better?

如果他们上面的代码可以变得更冗长并删除任何隐含内容,我会特别感兴趣,这样我就可以更好地理解它?

回答by Kim Stebel

_._1calls the method _1on the wildcard parameter _, which gets the first element of a tuple. Thus, sortWith(_._1 < _._1)sorts the list of tuple by their first element.

_._1调用_1通配符参数的方法_,它获取元组的第一个元素。因此,sortWith(_._1 < _._1)按元组的第一个元素对元组列表进行排序。

_++_calls the method ++on the first wildcard parameter with the second parameter as an argument. ++does concatenation for sequences. Thus .reduce(_++_)concatenates a list of sequences together. Usually you can use flattenfor that.

_++_++使用第二个参数作为参数调用第一个通配符参数上的方法。++对序列进行连接。因此.reduce(_++_)将序列列表连接在一起。通常你可以使用flatten它。

回答by sepp2k

_1is a method name. Specifically tuples have a method named _1, which returns the first element of the tuple. So _._1 < _._1means "call the _1 method on both arguments and check whether the first is less than the second".

_1是一个方法名。具体来说,元组有一个名为 的方法_1,它返回元组的第一个元素。所以_._1 < _._1意思是“在两个参数上调用 _1 方法并检查第一个是否小于第二个”。

And yes, _++_concatenates both arguments (assuming the first argument has a ++method that performs concatenation).

是的,_++_连接两个参数(假设第一个参数有一个++执行连接的方法)。

回答by Dominic Bou-Samra

.reduce(_++_)

is really just:

真的只是:

.reduce{ (acc, n) => acc ++ n }