
下划线
Placeholder syntax
这个用法比较多,表示某一个参数。比如对collection调用方法map、filter、sortWith、foreach等等表示对每一个元素进行处理,甚至可以使用_.XXX方式
Scala represents anonymous functions with a elegant syntax. The _acts as a placeholder for parameters in the anonymous function. The _ should be used only once, But we can use two or more underscores to refer different parameters.
1 |
List(1,2,3,4,5).foreach(print(_)) |
1 |
List(1,2,3,4,5).foreach( a => print(a)) |
Here the _ refers to the parameter. The first one is a short form of the second one. Lets look at another example which take two parameters.
1 |
val sum = List(1,2,3,4,5).reduceLeft(_+_) |
1 |
val sum = List(1,2,3,4,5).reduceLeft((a, b) => a + b) |
There is a good post which explains the inner details of the above example.
Wildcard patterns
In Scala, pattern matching is somewhat similar to java switch statement. But it is more powerful.
1 |
def (x: Int): String = x match { |
In Scala, each selector will be matched with the patterns in the order they appear and the first match will be executed. _acts like a wildcard. It will match anything. Scala allows nested patterns, so we can nest the _also.Lets see another example that uses_ in nested pattern.
1 |
expr match { |
Wildcard imports
In scala, _acts similar to * in java while importing packages.
1 |
|
类的setter方法
In scala, a getter and setter will be implicitly defined for all non-private var in a object. The getter name is same as the variable name and _= is added for setter name. We can define our own getters and setters. Ok lets see an example which uses the getter and setters.
1 |
class Test { |
1 |
val t = new Test |
Converting call-by-name parameters to functions
Scala is a functional language. So we can treat function as a normal variable. If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.
1 |
class Test { |
用于将方法转换成函数
参考资料:




近期评论