开发者

Scala underscore minimal function

开发者 https://www.devze.com 2023-01-30 08:28 出处:网络
Let\'s create a value for the sake of this question: val a = 1 :: Nil 开发者_开发技巧 now, I can demonstrate that the anonymous functions can be written in shorthand form like this:

Let's create a value for the sake of this question:

val a = 1 :: Nil
开发者_开发技巧

now, I can demonstrate that the anonymous functions can be written in shorthand form like this:

a.map(_*2)

is it possible to write a shorthand of this function?:

a.map((x) => x)

my solution doesn't work:

a.map(_)


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.


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.


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 
0

精彩评论

暂无评论...
验证码 换一张
取 消