标签:new string one get 函数类型 匿名函数 file count option
val a = 1
val b=a match { *// a match { }返回值赋予变量 b
case 1 => "red"
case 2 => "green"
case _ => "Not Allowed" *//其他通配符 _
or
case unexpected => unexpected +"is Not ALLOWED"
} println(b) // 输出red
for(elem <- List(9,12.3,"spark","hadoop",‘Hello)) {
val value = elem match {
case i :Int if(i>=0) => i +"is an int value" *// 可以添加守卫(if)
case d:Double => d+"is a double value"
case s:String => s+"is a str value"
case _ => "This is an unexpected value"
}
println(value)
}
case calss Car(brand:String,price:Int)
val BYD = new Car("BYD",89000)
val BWM = new Car("BWM",1000000)
val DABEN = new Car("BEN",1200000)
for(car <-List(BYD,BWM,DABEN)) {
car match{
case Car("BWD”,89000) =>println("HELLO,BYD")
case Car("BWM",1000000) =>println("Hello,BWM")
case Car("BEN",1200000) => println("Hello,DABEN")
}
}
*//(引用值存在与否,不存在未None)
val books = Map("a"->1,"b"->2)
book.get("a") *//返回Option[Int] = Some(5)
book.get("c") *//返回Option[Int] = None
*//(函数如变量一样有类型和值)
def counter(a:Int):Int={a+=1} *//函数类型为: (Int)=>Int 参数只有一个时圆括号可省略`
//函数的值: (a) => {a+=1} 只有一条语句时大括号可省略
val a = (num:Int) => num*2 //将匿名函数赋值给变量a
a(3) //返回6
val addMore =(x:Int)=>x+more *//(每次函数调用都会创建新闭包,每个闭包会访问闭包创建时活跃的more变量)
var myList = List(1,2,3,4)
myList.filter(x=x>0) == myList.filter(_>0)
val f = (_: Int) +(_:Int)
f(5,10) = 15
1)for(elem<-myList) println(elem)
2) mylist.foreach(elem =>println(elem)) ==mylist.foreach(println) == mylist foreach println
val myMap = Map("a"->1,"b"->2)
1)for((k,v)<-myMap) printf("%s,%d",k,v)
2)myMap foreach {case(k,v) =>println(k+":" +v)}
myList.map(elem=>elem+1)
myList.map(elem=>(1,elem+1) //转换为(key,value)
flatmap(拍扁操作)// List("hadoop","hive").flatmap(s=>s.toList) == List(h,a,d,o,o.....)
books.filter(s =>s._2 contains 1) // s._2代表value s._1代表key
reduce操作(归约)
myList.reduceLeft(_+_) == ((1+2)+3)+4
myList.reduceRight(_-_) == 1-(2-(3-4))
myList.flod(10)(_*_) ==1*2*3*4*10 = 240
标签:new string one get 函数类型 匿名函数 file count option
原文地址:https://www.cnblogs.com/CYRgrowing1215/p/9547387.html