_在scala中使用的非常巧妙,有时候也不好理解,现在总结如下:
1._可以用来指定foreach循环体中当前循环变量的值。
val s = 1.to(10).map({ _ * 2 })
println(s)
2.作为偏函数的参数占位符使用:
val sum = (a: Int, b: Int, c: Int) => a + b + c
val f = sum(1, 2, _: Int)
println(f(3))
3.在match表达式中使用
def echoWhatYouGaveMe(x: Any): String = x match {
// constant patterns
case 0 => "zero"
case true => "true"
case "hello" => "you said 'hello'"
case Nil => "an empty List"
// sequence patterns
case List(0, _, _) => "a three-element list with 0 as the first element"
case List(1, _*) => "a list beginning with 1, having any number of elements"
case Vector(1, _*) => "a vector starting with 1, having any number of elements"
// tuples
case (a, b) => s"got $a and $b"
case (a, b, c) => s"got $a, $b, and $c"
// constructor patterns
// typed patterns
case s: String => s"you gave me this string: $s"
case i: Int => s"thanks for the int: $i"
case f: Float => s"thanks for the float: $f"
case a: Array[Int] => s"an array of int: ${a.mkString(" , ")}"
case as: Array[String] => s"an array of strings: ${as.mkString(" , ")}"
case list: List[_] => s"thanks for the List: $list"
case m: Map[_, _] => {
m.toString
}
case Person(first, "Alexander" ) => s"found an Alexander, first name = $first"
case Dog("Suka" ) => "found a dog named Suka"
// the default wildcard pattern
case _ => "Unknown"
}
case list: List[_] => s"thanks for the List: $list"
case m: Map[_, _] => m. toString
_ 表示具体存什么值我不关心,只是有值存在集合里面
4.为变量设置默认值
var num : Int = _
println(s"num=$num")
打印输出num=0, _会根据数据类型选择默认值
5._表示导入包中的所有类型,相当于java导入中的*
import akka.actor._
import scala.concurrent.duration._