类getter和setter 如果字段定义是private[this], 字段是私有的,但不生成getter和setter方法. class Counter { private[this] var value = 0 } 如果字段定义是私有的(private),则getter和setter方法也是私有的. class Counter { private var value = 0 } 如果字段定义没有修饰符, 则字段是私有的,getter和setter方法是共有的. class Counter…
类继承: 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…
嵌套类: 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…
类 主构造器: class Person (var name: String){ } 主构造参数可以不带val或者var,如果没有被其他方法使用,则不保存为字段. 如果被其他方法使用,则被升格为字段,是private[this] val字段效果. 私有主构造: class Person private (var name: String){ } 辅助构造器: class Person (var name: String){ private var age = 0 def this(name: 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,位于相应的包下…
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…
构造映射: 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…
初始化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) } }…