Here is documentation about Predef
, but there is no word about identity. What is this function used for? And what it does?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With