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)

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...