参见英文答案 >
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)