scala中{_ =>}和_ = somefunctionname()的含义或用法是什么?

use*_*177 2 functional-programming scala

在问题中,为什么人们在scala中以最混乱的方式编写代码,如同

    _ = function1(arg1, arg2)
Run Code Online (Sandbox Code Playgroud)

    anObject.method(arg1, arg2) { _ => } 
Run Code Online (Sandbox Code Playgroud)

我不明白它的作用.

Ole*_*cov 14

第一个问题与monadic风格有关.在内部for理解中,不可能简单地调用函数.

for {
    x <- getList // <- I don't need this x!
    y = func(42)
    println(y) // <- I cannot do this!
} yield y
Run Code Online (Sandbox Code Playgroud)

但是,有时您对结果不感兴趣,因此不想给它起个名字.

至少Scala允许您使用下划线放弃这些结果:

for {
    _ <- getList // <- somewhat better
    y = func(42)
    _ = println(y) // <- somewhat dumb, but better than not being able to
} yield y
Run Code Online (Sandbox Code Playgroud)

当您对函数的参数不感兴趣时​​,Scala还允许您使用下划线,例如:

List.tabulate(3, 3)((x, _) => x) // we omitted second argument
Run Code Online (Sandbox Code Playgroud)

生成3x3列表,所有行具有相同的编号

List(
  List(0, 0, 0),
  List(1, 1, 1),
  List(2, 2, 2)
)
Run Code Online (Sandbox Code Playgroud)

最后,一个没有语句的块被认为是一个块返回Unit(就像void在java中一样)

作为一个不太抽象的示例,您可以考虑在评估时执行某些操作的迭代器:

val it = Iterator.from(1).map(x => { println(s"x is $x"); x }).take(3)
Run Code Online (Sandbox Code Playgroud)

迭代器是懒惰的,所以在我们将它转​​换为集合或调用之前不会发生任何事情foreach.如果我们只关心副作用,可以写:

it.foreach { _ => }
Run Code Online (Sandbox Code Playgroud)

只有在看到此输出后:

x is 1
x is 2
x is 3
Run Code Online (Sandbox Code Playgroud)