Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Predef.identity do in scala?

Tags:

Here is documentation about Predef, but there is no word about identity. What is this function used for? And what it does?

like image 999
Cherry Avatar asked Feb 09 '15 10:02

Cherry


1 Answers

It's just an instance of the identity function, predefined for convenience, and perhaps to prevent people from redefining it on their own a whole bunch of times. identity simply returns its argument. It can be handy sometimes to pass to higher-order functions. You could do something like:

scala> def squareIf(test: Boolean) = List(1, 2, 3, 4, 5).map(if (test) x => x * x else identity)  squareIf: (test: Boolean)List[Int]  scala> squareIf(true) res4: List[Int] = List(1, 4, 9, 16, 25)  scala> squareIf(false) res5: List[Int] = List(1, 2, 3, 4, 5) 

I've also seen it used as a default argument value at times. Obviously, you could just say x => x any place you might use identity, and you'd even save a couple characters, so it doesn't buy you much, but it can be self-documenting.

like image 162
acjay Avatar answered Oct 06 '22 01:10

acjay