加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:23:18 所属栏目:安全 来源:网络整理
导读:参见英文答案 What are all the uses of an underscore in Scala?????????????????????????????????????8个 在下面的代码中,下划线字符的使用的分类(或技术名称)是什么? scala def f: Int = Int = _ + 1f: Int = Intscala f(2)res0: Int = 3 解决方法 从 Fu
参见英文答案 > 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读