-
存在性類型:Existential types
val site = List(Option("Runoob"),Option(12),None) //Option[_]表示Option集合里可以是各種類型韧掩,應(yīng)為上面是字符串志笼,數(shù)字類型,也可以用Option[Any]來替換 def test(l:List[Option[_]]):Unit={ for(v<-l) { print(v.getOrElse("默認(rèn)值")) } } test(site)
-
臨時(shí)變量:Ignored variables
val _ = 5
-
臨時(shí)參數(shù):Ignored parameters
List(1, 2, 3). foreach { _ => println("Hi") }
-
通配模式:Wildcard patterns
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 _ => } //模式匹配 abstract class Item case class Product(description: String, price: Double) extends Item case class Bundle(description: String, discount: Double, items: Item*) extends Item def price(it: Item): Double = it match { case Product(_, p) => p //這里注釋下map(price _) 注意什么都沒有草描,_表示的是Product對象堪澎,取他的屬性price,不知道為什么要這么寫~~ case Bundle(_, disc, its @ _*) => its.map(price _).sum * (100-disc) /100 //這里@表示將嵌套的值綁定到變量its } //測試 val bun2 = Bundle("Appliance sale",10.0,Product("Haier Refrigerato", 3000.0),Product("Geli air conditionor",2000.0)) println(price(bun2))
-
通配導(dǎo)入:Wildcard imports
import java.util._
-
隱藏導(dǎo)入:Hiding imports
// 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 => _ , _ }
-
連接字母和標(biāo)點(diǎn)符號(hào):Joining letters to punctuation
def bang_!(x: Int) = 5
-
偏應(yīng)用函數(shù):Partially applied functions
def fun = { // Some code } val funLike = fun _ List(1, 2, 3) foreach println _ 1 to 5 map (10 * _) foo _ // Eta expansion of method into method value foo(_) // Partial function application Example showing why foo(_) and foo _ are different: trait PlaceholderExample { def process[A](f: A => Unit) val set: Set[_ => Unit] set.foreach(process _) // Error set.foreach(process(_)) // No Error }
-
初始化默認(rèn)值:default value
var i: Int = _
作為參數(shù)名:
//訪問map
var m3 = Map((1,100), (2,200))
for(e<-m3) println(e._1 + ": " + e._2)
m3 filter (e=>e.1>1)
m3 filterKeys (>1)
m3.map(e=>(e._1*10, e._2))
m3 map (e=>e._2)
//訪問元組:tuple getters
(1,2)._2
- 參數(shù)序列:parameters Sequence
*作為一個(gè)整體,告訴編譯器你希望將某個(gè)參數(shù)當(dāng)作參數(shù)序列處理。例如val s = sum(1 to 5:)就是將1 to 5當(dāng)作參數(shù)序列處理。
//Range轉(zhuǎn)換為List
List(1 to 5:_)
//Range轉(zhuǎn)換為Vector
Vector(1 to 5: _*)
//可變參數(shù)中
def capitalizeAll(args: String*) = {
args.map { arg =>
arg.capitalize
}
}
val arr = Array("what's", "up", "doc?")
capitalizeAll(arr: _*)