Predef.identity 在 Scala 中有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28407482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does Predef.identity do in scala?
提问by Cherry
回答by acjay
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. identitysimply returns its argument. It can be handy sometimes to pass to higher-order functions. You could do something like:
它只是identity function 的一个实例,为了方便而预定义,也许是为了防止人们自己重新定义它很多次。identity简单地返回它的参数。有时传递给高阶函数会很方便。你可以这样做:
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 => xany 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.
我也看到它有时用作默认参数值。显然,您可以只说x => x您可能使用的任何地方identity,甚至可以保存几个字符,因此它不会给您带来太多好处,但它可以是自我记录的。
回答by Artyom Kozhemiakin
Besides what acjayhave already mentioned, Identity function is extremely useful in conjunction with implicit parameters.
除了acjay已经提到的,Identity 函数与隐式参数结合使用非常有用。
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.
在这种情况下,当 B <: A 的某些实例作为函数第一个参数传递时,Identity 函数将用作隐式转换器。
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
如果您不熟悉隐式转换以及如何使用隐式参数来链接它们,请阅读:http: //docs.scala-lang.org/tutorials/FAQ/chaining-implicits.html

