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.
acjay Feb 09 '15 at 10:31 2015-02-09 10:31
source share