標籤:style class 使用 strong string 類
Chapter1 and Chapter2
方法定義:
def methodName(param1: ParamType, param2: ParamType2, [maybe more]): ReturnType = {
// method body
}
函數式編程中一個約定俗成的說法就是,方法會返回一個值,不然一個方法的存在就是在產生副作用,而避免副作用是函數式編程的一個初衷。
數組的訪問:
scala中的數組是Array[ContentType],聲明一個數組的時候需要指定數組的大小和所包含的元素的類型:
val arr = new Array[Int](3)
or
val arr = Array[Int](3)
or
val arr = Array(1, 2, 3) //直接聲明並初始化
以上兩種方式都能夠產生一個數組對象arr,但是他倆產生對象的方式不同,new Array[Int](3)使用的是建構函式產生一個對象,而Array[Int](3)是調用的Array[Int]的apply方法返回一個arr數組對象。
something in English: In scala, we can instantiate objects, or classes, using new. When you instantiate an object in scala, you can parameterize(確定...的參數) it with values and types.
幾個有特殊約定的方法,但是他們僅僅是普通的方法而已:
apply(param1:ParamType),這個方法存在於一個class裡面的話,那麼這個類的對象(test)就可以調用test(param),實際讓調用的就是test.apply(param)方法。
update(param:ParamType),這個方法是一個對象方法update(param:ParamType),它對應著test(param) = 12中的=。
1::intList,這個::符號讀作cons,它是一個right operand(右運算元),也就是說方法的調用者是intList。標準是:如果一個方法以:結尾的話,那麼這個方法就是一個右運算元。
各式各樣的for:
for (arg <- args) { println(arg) } // arg是一個不可變的參數
for (i <- 0 to 2) { println(args(i)) } // i是一個不可變的參數
args.foreach(arg => println(arg)) // 據說這是最函數式編程的方式
集中縮減形式:
如果一個方法參數僅有一個語句,並且僅僅包含一個參數,那麼參數可以省略
args.foreach(arg => println(arg)) == args.foreach(println)
如果一個方法僅有一個參數,並且方法的調用者明確指定,那麼. 和 () 可以省略
1 + 2 == (1).+(2)
元組
元組的訪問是._X,且X是從1開始的,one-based。
Mutable Objects
Array
Immutable Objects
List, Tuple,
// by default, the Set will be immutable set,
var testSet = Set(1, 2, 3)
// testSet is a var, so it can be reasigned. testSet += 4 equals testSet = testSet + 4
testSet += 4
testSet + 4 實際上是會返回一個新的對象,然後賦值給testSet,而不是簡單地把4追加到原來的Set裡面。
import scala.collection.mutable.Set
val testSet = Set(1, 2, 3)
// mutable set 有+=這個方法,這個方法會把新的元素追加到set中,並返回原來的對象。
testSet += 4
也就是說,testSet並沒有被重新建立,而只是在原來的set中追加了一個新的元素。
val指的並不是指向的對象不能變化,而只是指向的地址不能變化。
說的更直白一點應該就是:val指向的對象不允許重新賦值,而var指向的對象可以重新賦值。
Because the set is mutable, there is no need to reassign movieSet, which is why it can be a val.
By contrast, using += with the immutable set in Listing 3.5 required reassigning jetSet, which is why it must be a var.
建立一個新的Set或者Map
如果是空的:
val testSet = Set[Int]() //這個()是必須的
val testMap = Map[Int, String]() // 同上