val 不可變
var 可變
建議使用val變量,因爲spark複雜系統中,需要大量網絡傳輸數據,若使用var會擔心值被錯誤更改。
val可自動識別類型
也可自己定義類型
申明多個變量
-
如果在函數體內遞歸調用函數自身,則必須手動給出函數的返回類型
-
在調用函數時,也可以不按照函數定義的參數順序來傳遞參數,而是使 用帶名參數的方式來傳遞。
sayHello(firstName = “Mick”, lastName = “Nina”, middleName = “Jack”)
- 還可以混合使用未命名參數和帶名參數,但是未命名參數必須排在帶名 參數前面。
sayHello(“Mick”, lastName = “Nina”, middleName = “Jack”)
val s = sum(1 to 5: _*)
**
- - 在Scala中,提供了lazy值的特性,也就是說,如果將一個變量聲明爲 lazy,則只有在第一次使用該變量時,變量對應的表達式纔會發生計算。 這種特性對於特別耗時的計算操作特別有用,比如打開文件進行IO,進
行網絡IO等。
scala.collection.mutable.Map(“Leo” -> 30, “Jen” -> 25,
“Jack” -> 23) / /創建一個可變的Map
// 創建一個不可變的Map
val ages = Map(“Leo” -> 30, “Jen” -> 25, “Jack” -> 23)
val ages = Map((“Leo”, 30), (“Jen”, 25), (“Jack”, 23))
- 在如果想要將一個已有的序列直接調用變長參數函數,是不對的。比如 val s = sum(1 to 5)。
正確爲sun(1 to 5:_*)
object test {
def sum(nums: Int*) = {
var res = 0
for (num <- nums) res += num
res
}
def main(args: Array[String]): Unit = {
print(sum(1 to 5:_*))
}
}
Array/ArrayBuffer的操作
object test {
val a = Array(1, 2, 3, 4, 5)
//val a = ArrayBuffer(1, 2, 3, 4, 5)
val b = a.filter(_ % 2 == 0).map(2 * _) //提取偶數且*2
def main(args: Array[String]): Unit = {
for (ele<-b)
println(ele)
}
}
- 自定義setter方法的時候一定要注意scala的語法限制,簽名、 =、參數間不能有空格
object test {
def main(args: Array[String]): Unit ={
val leo = new Student
print(leo.name)
leo.name = "leo1"
println(leo.name2)
}
}
class Student {
private var myName = "leo"
def name = "your name is " + myName
def name_=(newValue: String) { //構造函數
myName = newValue
}
def name2 = "your name is " + myName
}
相當於java的重載
object test {
def main(args: Array[String]): Unit ={
val leo = new Student("a",12)
leo.get
val leo2 = new Student("b")
leo2.get
}
}
class Student {
private var name = ""
private var age = 0
def this(name: String) {
this()
this.name = name
}
def this(name: String, age: Int) {
this(name)
this.age = age
}
def get=println(name+age)
}