Scala 趣题 1

What is the result of executing the following code?

List(1, 2).map { i => i + 1 }
List(1, 2).map { i => println("Hi"); i + 1 }
List(1, 2).map { _ + 1 }
List(1, 2).map { println("Hi"); _ + 1 }

 
























Explanation

Even though the _ simplification looks the same, in the second case it has a very different effect: the println statement is no longer part of the function body! Instead, the expression is evaluated when determining the function to be passed to map - as with all blocks, the last value is returned.


你可能感兴趣的:(scala)