標籤:

Scala基礎語法參考

/*n學慕課網上《Scala程序設計》課程跟著敲的代碼n作為代碼參考也是很好的n在scala_ide.org上下載eclipse IDE,新建一個worksheet,就可以像在xcode的playground那樣玩了,n就是如下所示,寫變數直接在右邊顯示結果n鏈接:scala集合文檔http://docs.scala-lang.org/zh-cn/overviews/collections/introductionnn函數式編程,核心是狀態不變n*/nnvar x = 1 //> x : Int = 1nval y = 2 //> y : Int = 2nlazy val z = x + y //> z: => Intnn//Byte Short Int Long Float Double Boolean Char Unitnval b:Byte = 10 //> b : Byte = 10nvar u:Unit = () //> u : Unit = ()nn//類型體系很別緻n//Any -> AnyVal, AnyRefn//AnyVal基本類型n//AnyRef引用類型n//Null/Nothing作為最後子類nndef foo = throw new Exception("") //> foo: => Nothingnnvar name = "123" //> name : String = 123nvar name2 = s"456 ${name}" //> name2 : String = 456 123nn//定義函數ndef function(param:Int):Int = {n 1n} //> function: (param: Int)Intndef function2(param:Int) = {n 1n} //> function2: (param: Int)Intn//調用函數nfunction2(1) //> res0: Int = 1n//能省略就省略的方法定義ndef func = 1 //> func: => Intnnif(true) 1 else 2 //> res1: Int = 1nn//循環nvar l = List("a", "b", "c") //> l : List[String] = List(a, b, c)nfor{n s <- ln s1 = s.toUpperCase()n if(s1.length == 1)//filtern}yield(s1) //> res2: List[String] = List(A, B, C)nn//try..catch..finallyntry{n Integer.parseInt("dog")n}catch{n case _ => 0n}finally{n println("oo")n} //> oon //| res3: Int = 0nn//match 類似 switchnval i = 1 //> i : Int = 1ni match {n case 1 => "one"n case 2 => "two"n case _ => "others"n} //> res4: String = onenn//Call By Value || Call By Namen//先確定參數的值,再執行函數n//還是直接把參數傳入函數,在函數中確定參數的值ndef test1(x:Int) = x //> test1: (x: Int)Intndef test2(x: => Int) = x //> test2: (x: => Int)Intnn//高階函數ndef operate(f: (Int,Int)=>Int)={n f(4,4)n} //> operate: (f: (Int, Int) => Int)Intnn//返回值是函數ndef greeting() = (name:String) => {"hello " + name}n //> greeting: ()String => Stringnn//柯里化ndef add(a: Int)(b:Int) = a + b //> add: (a: Int)(b: Int)Intnadd(2)(2) //> res5: Int = 4nnvar add3 = add(3)_ //> add3 : Int => Int = <function1>nnadd3(5) //> res6: Int = 8nnnn/*n 以下都是常用的集合n*/nval lista = List(1, 2, 3, 4) //> lista : List[Int] = List(1, 2, 3, 4)nval listb = 0 :: lista //> listb : List[Int] = List(0, 1, 2, 3, 4)nval listc = "x" :: "y" :: "z" :: Nil //> listc : List[String] = List(x, y, z)nnval listd = lista ::: listc //> listd : List[Any] = List(1, 2, 3, 4, x, y, z)nlista.head //> res7: Int = 1nlistc.tail //> res8: List[String] = List(y, z)nlista.isEmpty //> res9: Boolean = falsenn//編寫遞歸函數處理listndef deallist(l: List[Int]): String = {n if(l.isEmpty) ""n else l.head.toString + " " + deallist(l.tail)n} //> deallist: (l: List[Int])Stringndeallist(lista) //> res10: String = "1 2 3 4 "n//對list應用filternlista.filter(x=>x%2==1) //> res11: List[Int] = List(1, 3)nlista.filter(_%2==1) //> res12: List[Int] = List(1, 3)nn"99 Red Balloons".toList.filter(x=>Character.isDigit(x))n //> res13: List[Char] = List(9, 9)n//一直取直到..n"99 Red Balloons".toList.takeWhile(x=>x!=B) //> res14: List[Char] = List(9, 9, , R, e, d, )nn//對list應用mapnlistc.map(x=>x.toUpperCase) //> res15: List[String] = List(X, Y, Z)nlistc.map(_.toUpperCase) //> res16: List[String] = List(X, Y, Z)nn//二維數組nval liste = List(lista, List(4,5,6)) //> liste : List[List[Int]] = List(List(1, 2, 3, 4), List(4, 5, 6))n//把二維數組轉為一維nliste.flatMap(_.filter(_%2==0)) //> res17: List[Int] = List(2, 4, 4, 6)nn//reduce,參數為一個函數,該函數有兩個參數,倆參數與一個返回值這三者的類型都相同nlista.reduceLeft(_ + _) //> res18: Int = 10nn//foldn//不斷把值加上去nlista.foldLeft(0)(_ + _) //> res19: Int = 10n//不斷把值乘上去nlista.foldLeft(1)(_ * _) //> res20: Int = 24n//不斷把值連到字元串上nlista.foldLeft("")(_ + _) //> res21: String = 1234nn//range,用to或until(右閉或右開)n1 to 10 //> res22: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6,n //| 7, 8, 9, 10)n1 until 10 by 2 //> res23: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)nn//stream 惰性求值nval s = (1 to 10000).toStream //> s : scala.collection.immutable.Stream[Int] = Stream(1, ?)ns.head //> res24: Int = 1ns.tail //> res25: scala.collection.immutable.Stream[Int] = Stream(2, ?)nn//tuplen(1,2) //> res26: (Int, Int) = (1,2)n//類似資料庫里的一行記錄,可以作為函數的返回值,打包返回多個值nval alice = (1, "Alice", "Math", 95.5) //> alice : (Int, String, String, Double) = (1,Alice,Math,95.5)nalice._1 //> res27: Int = 1nndef sumSq(in : List[Int]):(Int,Int,Int)=n in.foldLeft((0,0,0))((t,v)=>(t._1+1, t._2+v, t._3+v*v))n //> sumSq: (in: List[Int])(Int, Int, Int)nnsumSq(lista) //> res28: (Int, Int, Int) = (4,10,30)nnn//mapnval map = Map(1 -> "David", 9->"Beckham") //> map : scala.collection.immutable.Map[Int,String] = Map(1 -> David, 9 -> Ben //| ckham)nmap(1) //> res29: String = Davidnmap.contains(1) //> res30: Boolean = truenmap.keys //> res31: Iterable[Int] = Set(1, 9)nmap.values //> res32: Iterable[String] = MapLike(David, Beckham)nmap + (10 -> "Zidane") //> res33: scala.collection.immutable.Map[Int,String] = Map(1 -> David, 9 -> Ben //| ckham, 10 -> Zidane)nmap - 1 //> res34: scala.collection.immutable.Map[Int,String] = Map(9 -> Beckham)nmap ++ List(7 -> "Ronaldo", 9 -> "Raul") //> res35: scala.collection.immutable.Map[Int,String] = Map(1 -> David, 9 -> Ran //| ul, 7 -> Ronaldo)nmap -- List(1,9,2) //> res36: scala.collection.immutable.Map[Int,String] = Map()nnn/*快速排序,好短!*/ndef sort(a:List[Int]):List[Int] =nif(a.length < 2) anelsensort(a.filter(_<a.head)) ++ a.filter(_==a.head) ++ sort(a.filter(_>a.head))n //> sort: (a: List[Int])List[Int]nnsort(List(3,1,2,5,2,7)) //> res37: List[Int] = List(1, 2, 2, 3, 5, 7)n

推薦閱讀:

什麼是真正的程序員?
XML 為什麼很重要?XML 解決了什麼問題?
依靠 IDE 會讓程序員的水平變差嗎?
如何學好 Visual Basic?
流計算框架 Flink 與 Storm 的性能對比

TAG:Scala | 编程 |