码迷,mamicode.com
首页 > 其他好文 > 详细

Scala语法(三)

时间:2018-08-28 13:04:24      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:new   string   one   get   函数类型   匿名函数   file   count   option   

模式匹配

1)match

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)

}

2) case类

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")
}
}

Option类型

*//(引用值存在与否,不存在未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}   只有一条语句时大括号可省略

匿名函数(Lamda表达式)

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)}

map操作

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.....)

filete操作

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))

flod操作(折叠)

myList.flod(10)(_*_) ==1*2*3*4*10 = 240

Scala语法(三)

标签:new   string   one   get   函数类型   匿名函数   file   count   option   

原文地址:https://www.cnblogs.com/CYRgrowing1215/p/9547387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!