快学Scala 第十七课 (trait 入门)】的更多相关文章

trait 入门: trait类似于java的接口,不过比java接口功能更强大,可以有实体成员,抽象成员,实体方法,抽象方法. 如果需要混入的特质不止一个用with关键字. 带有特质的对象:(特质可以随时被混入对象中) trait Logged { def log(msg: String){} } trait ConsoleLogger extends Logged { override def log(msg: String){ println(msg) } } class SavingsA…
初始化trait的抽象字段: trait Logged { println("Logged constructor") def log(msg: String){ println("Logged")} } trait FileLogger extends Logged { var filename: String override def log(msg: String) { println("filename:" + filename) } }…
trait的构造顺序: 首先调用超类构造器 特质构造器在超类构造器之后,类构造器之前执行 特质从左向右被构造 每个特质当中,父特质先被构造 如果多个特质共有一个父特质,而那个父特质已经被构造,则不会被再次构造 所有特质构造完毕,子类被构造 class Account { println("Account constructor") } trait Logged { println("Logged constructor") def log(msg: String){…
Scala 类型层级: 对象相等性: 和Java一样要重写equals方法和hashcode方法 class Student(val id: Int, val name: String) { override def equals(other: Any) = { val that = other.asInstanceOf[Student] if (that == null) false else id == that.id && name == that.name } override d…
类继承: class People { } class Emp extends People{ } 和Java一样,final的类不能被继承.final的字段和方法不能被override. 在Scala中重写一个非抽象方法必须使用override, 继承抽象方法前面加了override也没关系. abstract class Person { def say(s: String): Unit } class Worker extends Person{ override def say(s: S…
Scala包定义: 嵌套式: package a1 { class a1Class{ val age = 10 } package a2 { class PackageTest { def main(args: Array[String]): Unit = { println(new a1Class().age) } } } } 串联式: package com.citi.packageUtil 包对象: 包对象被编译成带有静态方法和字段的JVM类,名为package.class,位于相应的包下…
嵌套类: class Human { class Student{ val age = 10 } } object ClassDemo { def main(args: Array[String]): Unit = { val h = new Human val s = new h.Student println(s.age) } } 有时会遇到这种情况: class Human { class Student { def addS(s: Student) = { val ab = new Ar…
构造映射: val score = Map[String, Int]() val score1 = HashMap[String, Int]() val value1 = Map[String, Int]("aa" -> 1, "bb" -> 2) val value2 = Map[String, Int](("aa", 1), ("bb", 2)) 获取映射值: println(if(value2.contain…
Scala二维数组的定义: val arr2 = Array.ofDim[String](2, 2) arr2(0)(0) = "aa" arr2(1)(0) = "bb" for(i <- 0 until arr2.length; j <- 0 until arr2(0).length){ println(arr2(i)(j)) } Scala不规则数组定义: val tri = new Array[Array[Int]](2) tri(0) = ne…
定长数组定义: val ar = new Array[Int](10) val arr = Array("aa", "bb") 定长数组赋值: arr(0) = "cc" 变长数组定义: val ab = new ArrayBuffer[String]() val ab1 = ArrayBuffer[String]() 定长数组增加元素: ab += "aa" ab += ("bb", "cc&q…