What does Predef.identity do in scala?

There is documentation about Predef , but no word about identifier. What is this function for? And what is he doing?

+11
scala
Feb 09 '15 at 10:21
source share
2 answers

This is just an instance of the identification function , predefined for convenience, and perhaps so that people do not redefine it on their own a whole bunch of times. identity simply returns its argument. Sometimes it’s useful to switch to higher order functions. You can 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 also saw that from time to time it was used as the default argument value. Obviously, you could just say x => x anywhere you could use identity , and you would even keep a couple of characters, so it won’t buy you a lot, but it can be self-documenting.

+14
Feb 09 '15 at 10:31
source share

In addition to what acjay has already mentioned, the Identity function is extremely useful in combination with implicit parameters.

Suppose you have a function like this:

 implicit def foo[B](b: B)(implicit converter: B => A) = ... 

In this case, the Identity function will be used as an implicit converter when any instance of B <: A is passed as the first argument to the function.

If you are not familiar with implicit conversions and how to use implicit parameters to chain them, read the following: http://docs.scala-lang.org/tutorials/FAQ/chaining-implicits.html

+4
Mar 06 '16 at 19:54
source share



All Articles