Predef.identity 在 Scala 中有什么作用? [英] What does Predef.identity do in scala?

查看:33
本文介绍了Predef.identity 在 Scala 中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是关于的文档Predef,但没有关于身份的字眼.这个函数是干什么用的?它有什么作用?

Here is documentation about Predef, but there is no word about identity. What is this function used for? And what it does?

推荐答案

这只是身份函数的一个实例,预定义是为了方便,也许是为了防止人们自己多次重新定义它.identity 只是返回它的参数.有时传递给高阶函数会很方便.你可以这样做:

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)

我也看到它有时用作默认参数值.显然,你可以直接说 x =>;x 任何你可能使用 identity 的地方,你甚至可以保存几个字符,所以它不会给你带来太多好处,但它可以自我记录.

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.

这篇关于Predef.identity 在 Scala 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆