List magic operation
1. Operators::, .::, :+, +:, :::
def specialCharacter(): Unit = {
val list0 = List(1, 2, 3)
// :: 用于的是向队列的头部追加数据,产生新的列表, x::list,x就会添加到list的头部
val list1 = 4 :: list0
println(list1) //List(4, 1, 2, 3)
// .:: 这个是List的一个方法;作用和上面的一样,把元素添加到头部位置; list.::(x);
val list2 = list0.::(5)
println(list2) //List(5, 1, 2, 3)
// :+ 用于在List尾部追加元素; list :+ x;
val list3 = list0 :+ 6
println(list3) //List(1, 2, 3, 6)
// +: 用于在list的头部添加元素;
val list4 = "A" +: "B" +: Nil //Nil是一个空的List,定义为List[Nothing]
println(list4) //List(A, B)
// ::: 用于连接两个List类型的集合 list ::: list2
val list5 = list0 ::: list4
println(list5) //List(1, 2, 3, A, B)
// ++ 用于连接两个集合,list ++ list2
val list6 = list0 ++ list4
println(list6) //List(1, 2, 3, A, B)
println(list0) //List(1, 2, 3)
}
1.1 Import wildcards
When importing packages, use _
instead:
//Scala
import java.util._
Class members in Scala must be explicitly initialized, and the compiler can automatically set the default value for you:
class Apple{
//String类型的默认值为null
var s: String = _
}
1.3 Variable parameters
But in Scala, you must tell the compiler explicitly whether you want to pass in the collection as an independent parameter or pass in the elements of the collection. If the latter, use underscores:
printArgs(List("a", "b"): _*)
1.4 Type wildcards
def printList(list: List[_]): Unit ={
list.foreach(elem => println(elem + " "))
}
2 Pattern matching
2.1 Default matching
str match{ case "1" => println("match 1") case _ => println("match default") }
Reference:
https://my.oschina.net/joymufeng/blog/863823