Scala underscore minimal function

不打扰是莪最后的温柔 提交于 2019-11-26 21:00:31

Your first shorthand form can also be written point-free

a map (2*)

Thanks to multiplication being commutative.

As for (x) => x, you want the identity function. This is defined in Predef and is generic, so you can be sure that it's type-safe.

Daniel C. Sobral

For the record, a.map(_) does not work because it stands for x => a.map(x), and not a.map(x => x). This happens because a single _ in place of a parameter stands for a partially applied function. In the case of 2*_, that stands for an anonymous function. These two uses are so close that is very common to get confused by them.

You should use identity function for this use case.

a.map(identity)

identity is defined in scala.Predef as:

implicit def identity[A](x: A): A = x 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!