SCALA學習筆記(一),SCALA學習筆記(
變數
擷取變數的值是一個耗時的工作時,可以考慮使用lazy var.
lazy val forLater = someTimeConsumingOperation()
scala> val first :: rest = List(1, 2, 3)
first: Int = 1
rest: List[Int] = List(2, 3)
函數定義
“=”並不只是用來分割函數簽名和函數體的,它的另一個作用是告訴編譯器是否對函數的傳回值進行類型推斷!如果省去=,則認為函數是沒有傳回值的!
比如:
scala> def myFirstMethod() = { “exciting times ahead” }
myFirstMethod: ()java.lang.String
scala> def myFirstMethod(){ “exciting times ahead” }
myFirstMethod: ()Unit
函數字面量:FUNCTION LITERALS
In Scala you can also pass a function as a parameter to another function, and most of the time in those cases I provide an inline definition of the function. This passing of functions as a parameter is sometimes loosely called closure (passing a function isn’t always necessarily closure; you’ll look into that in chapter 4). Scala provides a shorthand way to create a function in which you write only the function body, called function literals.
簡單地說就是: 函數字面量就是省去了函數簽名(主要就是函數名和參數聲明)只留下函數體的一段代碼!注意,這個還不同於匿名函數,匿名函數只是沒有函數名,但是參數聲明是不會省略的!對於函數字面量來講,因為省略了參數聲明,當函數體內需要使用到參數時,就會使用一個底線來指代!這也可以說是函數字面量的一個特徵了!
例如:
//很顯然,花括弧中的部分是一個匿名函數scala> evenNumbers.foldLeft(0) { (a: Int, b:Int) => a + b } //花括弧中的部分依然是匿名函數,只是省去了參數的型別宣告scala> evenNumbers.foldLeft(0) { (a, b) => a + b } //演化到這個版本時,發生了一些實質性的變化://參數聲明也被省略了,很顯然,我們再也不能將其稱之為匿名函數了!//隨著參數聲明的取消,帶來了一個問題:如何在函數體內指代和標示參數呢?scala> evenNumbers.foldLeft(0) { _ + _ }
在scala裡, 一個底線代表一個參數!
閉包:Closure
A closure is any function that closes over the environment in which it’s defined. For example, closure will keep track of any variable changes outside the function that are being referred to inside the function.
def breakable(op: => Unit) { … }
What’s this op: => Unit? The special right arrow (=>) lets Scala know that the breakable function expects a function as a parameter. The right side of the => defines the return type of the function—in this case it’s Unit (similar to Java void)—and op is the name of the parameter. Because you haven’t specified anything on the left side of the arrow, it means that the function you’re expecting as a parameter doesn’t take any parameter for itself.
如果我們需要的傳入參數是一個代參數且有傳回值的函數呢? 這樣的函數作參數應該如何描述呢?
def foldLeft(initialValue: Int, operator: (Int, Int) => Int)= { … }
讓我們這樣來理解吧:既然對於函數式程式設計語言來說,函數是第一位(first class)的,它可以像其他資料類型一樣被使用,那麼當它作為函數的參數時,我們需要約定一個文法來描述這個”參數”(實際上是一個函數)的”類型”(實際上應該是這個函數的”元資訊“),那麼對於一個函數來說,它的”類型“應該怎樣去描述呢?從語言的設計者角度來考慮的話,那當然最合理的描述方式是:陳述出這個函數的參數類型和它的傳回值類型!這也正是operator: (Int, Int) => Int)所做的!簡單明了,合情合理!
數組
scala> val array = new Array[String](3)array: Array[String] = Array(null, null, null)scala> array(0) = "This"scala> array(1) = "is"scala> array(2) = "mutable"
對於給數組賦值的語句:array(0) = “This”,這裡要說明的是:不同於java中的array[0] = “This” 在scala中,[]永遠是用來制定參數類型的!
FOR迴圈
val files = new java.io.File(".").listFiles for(file <- files) { val filename = file.getName if(fileName.endsWith(".scala")) println(file)}
The only thing that looks different from for loops in Java or C# is the expression file <- files. In Scala this is called a generator, and the job of a generator is to iterate through a collection.
scala> val aList = List(1, 2, 3)aList: List[Int] = List(1, 2, 3)scala> val bList = List(4, 5, 6)bList: List[Int] = List(4, 5, 6)scala> for { a <- aList; b <- bList } println(a + b)567678789 scala> val result = for { a <- aList; b <- bList } yield a + bresult: List[Int] = List(5, 6, 7, 6, 7, 8, 7, 8, 9)scala> for(r <- result) println(r)567678789
註:for語句的花括弧{}並不是必須的,你完全可以使用().
模式比對:Pattern Matching
模式比對,樣本一:
ordinal(args(0).toInt)def ordinal(number:Int) = number match { case 1 => println("1st") case 2 => println("2nd") case 3 => println("3rd") case 4 => println("4th") case 5 => println("5th") case 6 => println("6th") case 7 => println("7th") case 8 => println("8th") case 9 => println("9th") case 10 => println("10th") case _ => println("Cannot do beyond 10")}
case _ to match everything else.
模式比對,樣本二:
在下面的這個例子中展示了scala一些內建的預定義的Pattern,專門應用於case上的,例如下面例子中的:f,s, rest
scala> List(1, 2, 3, 4) match {case f :: s :: rest => List(f, s)case _ => Nil}res7: List[Int] = List(1, 2)
模式比對,樣本三:
val suffixes = List("th", "st", "nd", "rd", "th", "th", "th","th", "th","th");println(ordinal(args(0).toInt))def ordinal(number:Int) = number match { case tenTo20 if 10 to 20 contains tenTo20 => number + "th" case rest => rest + suffixes(number % 10)}
類:Class
What val and var do is define a field and a getter for that field, and in the case of var an additional setter method is also created. When both of them are missing, they’re treated as private instance values, not accessible to anyone outside the class.
對於Class的field的修飾符有如下約定: