Here is documentation about Predef
, but there is no word about identity. What is this function used for? And what it does?
问题:
回答1:
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.
回答2:
Besides what acjay have already mentioned, Identity function is extremely useful in conjunction with implicit parameters.
Suppose you have some function like this:
implicit def foo[B](b: B)(implicit converter: B => A) = ...
In this case, Identity function will be used as an implicit converter when some instance of B <: A is passed as a function first argument.
If you are not familiar with implicit conversions and how to use implicit parameters to chain them, read this: http://docs.scala-lang.org/tutorials/FAQ/chaining-implicits.html