列表
使用List(“”,“”,“”)去聲明
sliding 和 groued表示迭代器
val iter = List("Hadoop", "Spark", "Scala") sliding 2// sliding 和 groued 是有區別的while (iter.hasNext){println(iter.next())}for (elem <- iter){println(elem)}
可變數組
def main(args: Array[String]): Unit = {import scala.collection.mutable.ArrayBufferval aMutableArr = ArrayBuffer(10,20,30)println(aMutableArr)aMutableArr += 40println(aMutableArr)aMutableArr.insert(2,60)println(aMutableArr)aMutableArr -= 40println(aMutableArr)}
元組
def main(args: Array[String]): Unit = {val tuple = ("Bigdata",2022,45.0)println(tuple)println(tuple._1)println(tuple._2)}
構造器
class Counter{private var value = 0 // value用來儲存計數器的起始值private var name = "" //表示計數器的名稱private var mode = 1 // mode用來表示計數器的類型(比如,1表示部署計數器,2表示時間計數器def this(name: String){ // 第一個輔助計數器this() // 調用主構造器this.name = name}def this(name: String,mode:Int){// 第二個輔助構造器this(name) // 調用前一個輔助構造器this.mode = mode}def increment(step: Int):Unit = {value += step}def current():Int = {value}def info():Unit = {printf("name:%s and mode is %d\n",name,mode)}}object Main {def main(args: Array[String]): Unit = {val myCounter = new Counter // 主構造器val counter1 = new Counter("Runner")val counter2 = new Counter("Timer",2)myCounter.info() // 顯示計數器信息myCounter.increment(1) // 設置步長println(myCounter.current)counter1.info()counter1.increment(2)println(counter1.current)counter2.info()counter2.increment(3)println(counter2.current)}
}
- 構造器在參數中
class Counter(val name:String = "",val mode:Int = 1){private var value = 0 // value用來儲存計數器的起始值def increment(step: Int):Unit = {value += step}def current():Int = {value}def info():Unit = {printf("name:%s and mode is %d\n",name,mode)}}object Main {def main(args: Array[String]): Unit = {val myCounter = new Counter // 主構造器val counter1 = new Counter("Runner")val counter2 = new Counter("Timer",2)myCounter.info() // 顯示計數器信息myCounter.increment(1) // 設置步長println(myCounter.current)counter1.info()counter1.increment(2)println(counter1.current)counter2.info()counter2.increment(3)println(counter2.current)}
}
單例對象
Scala并沒有提供Java那樣的靜態方法和靜態字段,但是可以采用object關鍵字實現單例對象,具備和Java靜態方法相同的功能。
object Person{private var lastId = 0 // 身份證號def nerPersonId()={lastId += 1lastId}
}
伴生類和伴生對象
class Person{private val id = Person.newPersonId() // 調用了伴生對象中的方法private var name = ""def this(name: String){this()this.name = name}def info() {printf("the id of %s is %d.\n",name,id)}
}object Person{private var lastId = 0 // 身份證號def newPersonId()={lastId += 1lastId}
}object Main {def main(args: Array[String]): Unit = {val person1 = new Person("ziyu")val person2 = new Person("Minxing")person1.info()person2.info()}
}
apply方法和update方法
- 我們經常會用到對象的apply方法和update方法,雖然我們表面上并沒有察覺,但是實際上,在Scala中,apply方法和update方法都會遵循相關的約定被調用
- apply方法:用括號傳遞給變量(對象)一個或多個參數時,Scala會把它轉換成對apply方法的調用
class TestApplyclass{def apply(param:String):String = {println(param)return "hello world"}
}object Main {def main(args: Array[String]): Unit = {val myObject = new TestApplyclassprintln(myObject("param1"))}
}
這種方式生成對象 會自動調用apply方法
class Main{}class ApplyTest{def apply() = println("apply method id class is called!")def greetingOfclass():Unit = {println("Greeting method in class is called.")}
}object ApplyTest{def apply() = {println("apply method in object is called")new ApplyTest() // 這行不會自動調用ApplyTest伴生類的apply方法}
}object Main {def main(args: Array[String]): Unit = {val a = ApplyTest() // 這里會調用伴生對象中的apply方法a.greetingOfclass()a() // 這里會調用半生類中的apply方法}
}
- update方法:當對帶有括號并包括一到若干參數的對象進行賦值時,編譯器將調用對象的update方法,在調用時,是把括號里的參數和等號右邊的對象一起作為update方法的輸入參數來執行調用
抽象類和繼承
abstract class Car{val carBrand: Stringdef infodef greeting() {println("welcome to my car!")}
}
class BMWCar extends Car{override val carBrand: String = "BMW"def info(){println(this.carBrand)}override def greeting(){println("welcome to BMW car!")}}
特質
特質概述
- Java中提供了接口,允許一個類實現任意數量的接口
- 在Scala中沒有接口的概念,二十提供了“特質(trait)”,它不僅實現了接口的功能,還具備了很多其他的特性
- Scala的特質,是代碼重用的基本單元,可以同時擁有抽象方法和具體方法
- Scala中,一個類只能繼承自一個超類,卻可以實現多個特質,從而重用特質中的方法和字段,實現了多重繼承
trait CarId{var id:Intdef currentId():Int //定義了一個抽象方法
}class BYDCarId extends CarId{override var id = 10000 // BYD汽車編號從10000開始def currentId():Int = {id += 1;id}
}
class BMWCarId extends CarId{override var id = 20000 // BMW汽車編號從20000開始def currentId():Int = {id += 1;id}
}