Scala 下划线的用途
所属分类 scala
浏览量 796
val list = List(1,2)
// List[String] = List(a, a)
list.map(item => "a")
list.map(_ => "a")
类型通配符
def printList(list: List[_]): Unit ={
list.foreach(item => println(item + " "))
}
定义偏函数
def sum(a: Int, b: Int, c: Int) = a + b + c
val b = sum(1, _: Int, 3)
// 6
b(2)
下划线 方法转函数
val func1 = method1 _
不加下划线 则是调用
scala 方法和函数的区别
临时变量Ignored variables
val _ = 5
val (a, _) = (1, 2)
变量初始化
// String类型的默认值为null
var str : String = _
包导入
//Java
import java.util.*;
//Scala
import java.util._
隐藏导入
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
访问tuple元素
val t = ("a","b")
println(t._1,t._2)
索引从1开始
简写函数
如果函数的参数在函数体只出现一次,可以用下划线代替
val nums = List(1, 2, 3)
nums.map(_ + 1)
// 倒序
nums.sortWith(_>_)
nums.filter(_ % 2 == 0)
List(1, 2, 3) foreach { _ => println("hello") }
List(1, 2, 3) foreach {println(_) }
List(1, 2, 3) foreach(println)
List(1, 2, 3) foreach println _
1 to 5 map (10 * _)
List("foo", "bar", "baz").map(_.toUpperCase())
nums reduceLeft(_+_)
nums reduce (_ + _)
nums reduceLeft(_ max _)
nums.exists(_ > 2)
nums.takeWhile(_ < 8)
用于模式匹配
Some(5) match { case Some(_) => println("Yes") }
match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ => "other"
}
访问map key 和 value
var m = Map((1,100), (2,200))
for(e<-m) println(e._1 + ": " + e._2)
m filter (e=>e._1>1)
m filterKeys (_>1)
m.map(e=>(e._1*10, e._2))
m map (e=>e._2)
参数序列 parameters Sequence _*作为一个整体 将某个参数当作参数序列处理
List(1 to 3:_*)
List[Int] = List(1, 2, 3)
List(1 to 3)
List[scala.collection.immutable.Range.Inclusive] = List(Range 1 to 3)
//匹配以0开头,长度为三的列表
expr match {
case List(0, _, _) => println("found it")
case _ =>
}
//匹配以0开头,长度任意的列表
expr match {
case List(0, _*) => println("found it")
case _ =>
}
//匹配元组元素
expr match {
case (0, _) => println("found it")
case _ =>
}
上一篇
下一篇
Scala map与flatMap
Scala 集合操作
play scala hello world tutorial
scala 匿名函数
scala函数定义及使用
play框架web编程实例