gpt4 book ai didi

scala - Int => Int = _ + 1 中_的用法是什么

转载 作者:行者123 更新时间:2023-12-04 22:28:49 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What are all the uses of an underscore in Scala?

(7 个回答)


4年前关闭。




在下面的代码中,下划线字符的使用分类(或技术名称)是什么?

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)

关于scala - Int => Int = _ + 1 中_的用法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41487691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com