微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

scala – 在Int => Int = _ 1 中_的用法是什么

参见英文答案 > What are all the uses of an underscore in Scala?                                    8个
在下面的代码中,下划线字符的使用的分类(或技术名称)是什么?

scala> def f: Int => Int = _ + 1
f: Int => Int

scala> f(2)
res0: Int = 3

解决方法

Functional Programming in Scala

… sometimes called underscore Syntax for a function literal,we are
not even bothering to name the argument to the function,using _
represent the sole argument. When using this notation,we can only
reference the function parameter once in the body of the function (if
we mention _ again,it refers to another argument to the function)

在你的情况下,做:

def f: Int => Int = _ + 1

会是这样的:

def f: Int => Int = x => x + 1

这似乎是不必要的,但是将匿名函数传递给更高阶函数(这些函数函数作为参数)变得非常方便:

def higherOrder(f: Int => Int) = { /* some implementation */ }

// Using your function you declared already
higherOrder(f)  

// Passing an anonymous function
higherOrder((x: Int) => x + 1)
higherOrder((x) => x + 1)
higherOrder(x => x + 1)

// Passing an anonymous function with underscore Syntax
higherOrder(_ + 1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐