Scala语法

Posted cyrgrowing1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala语法相关的知识,希望对你有一定的参考价值。

模式匹配

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语法的主要内容,如果未能解决你的问题,请参考以下文章

大数据学习06 Scala的基础语法

Scala 基础语法

在下面的代码片段中的剩余 ='passthrough' 处的代码中出现语法错误

尝试理解 Kafka Scala 语法

scala语法基础1

Scala简明语法