scala 中下划线的含义
1、Placeholder syntax(占位符,函数参数的占位符)
Multiple underscores mean multiple parameters, not reuse of a single parameter repeatedly.
The first underscore
represents the first parameter, the second underscore the second parameter,
the third underscore the third parameter, and so on.
例如:
正确示范:
scala> (1 to 9).map(_*2)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14
, 16, 18)
如果要映射成一个元组的集合
x=>(x,x*x)
比如
:1->(1,1),2->(2,4) ,3->(3,9) ... 9->(9,81)
可以这样:
scala> (1 to 9).map(x=>(x,x*x))
res2: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,1), (2,4), (
3,9), (4,16), (5,25), (6,36), (7,49), (8,64), (9,81))
这种情况下,就不能使用_来代替,因为多个下划线意思多个参数,而不是单个参数的重复使用
错误示范:
scala> (1 to 9).map(x=>(_,_*_))
<console>:8: error: missing parameter type for expanded function ((x$1) => scala
.Tuple2(x$1, ((x$2, x$3) => x$2.$times(x$3))))
(1 to 9).map(x=>(_,_*_))
所以这种情况下的使用条件是:
参数在右侧只能出现一次,可以用_替换,多个参数多个_
2、Partially applied functions(部分应用函数)
A partially applied function is an expression in which you don’t supply all
of the arguments needed by the function. Instead, you supply some, or none,
of the needed arguments
例如:
对于如下sum函数定义
scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (a: Int,b: Int,c: Int)Int
可以有2种情况应用函数sum的部分功能
情况1:不带参数(None of arguments)
scala> val a = sum _
a: (Int, Int, Int) => Int = <function3>
scala> a(1, 2, 3)
res11: Int = 6
情况2:带入部分需要的参数(some of arguments)
scala> val b = sum(1, _: Int, 3)
b: (Int) => Int = <function1>
scala> b(2)
res13: Int = 6
3、其它含义
最难理解的可能就上面的2个用法了,其它下划线_的含义可以参考如下:
http://www.zhihu.com/question/21622725/answer/21588672
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala
http://ananthakumaran.in/2010/03/29/scala-underscore-magic.html