类 对象 继承 参数化类型 特质 模式匹配(match case类) 包
类的定义
构造器
//代码文件为/usr/local/scala/mycode/Counter2.scala
class Counter {
private var value = 0
private var name = ""
private var step = 1 //计算器的默认递进步长
println("the main constructor")
def this(name: String){ //第一个辅助构造器
this() //调用主构造器
this.name = name
printf("the first auxiliary constructor,name:%s\n",name)
}
def this (name: String,step: Int){ //第二个辅助构造器
this(name) //调用前一个辅助构造器
this.step = step
printf("the second auxiliary constructor,name:%s,step:%d\n",name,step)
}
def increment(step: Int): Unit = { value += step}
def current(): Int = {value}
}
单例对象
//代码文件为/usr/local/scala/mycode/Person1.scala
class Person(val name:String){
private val id = Person.newPersonId() //调用了伴生对象中的方法
def info() {
printf("The id of %s is %d.\n",name,id)
}
}
object Person {
private var lastId = 0 //一个人的身份编号
def newPersonId() = {
lastId +=1
lastId
}
def main(args: Array[String]) {
val person1 = new Person("Lilei")
val person2 = new Person("Hanmei")
person1.info()
person2.info()
}
}
特质
//代码文件为/usr/local/scala/mycode/Bird2.scala
trait Flyable {
var maxFlyHeight:Int //抽象字段
def fly() //抽象方法
def breathe(){ //具体的方法
println("I can breathe")
}
}
trait HasLegs {
val legs:Int //抽象字段
def move(){printf("I can walk with %d legs",legs)}
}
class Animal(val category:String){
def info(){println("This is a "+category)}
}
class Bird(flyHeight:Int) extends Animal("Bird") with Flyable with HasLegs{
var maxFlyHeight:Int = flyHeight //重载特质的抽象字段
val legs=2 //重载特质的抽象字段
def fly(){
printf("I can fly at the height of %d",maxFlyHeight)
}//重载特质的抽象方法
}
match语句
//代码文件为/usr/local/scala/mycode/TestMatch1.scala
import scala.io.StdIn._
println("Please input a country:")
val country=readLine()
country match{
case "China" => println("中国")
case "America" => println("美国")
case "Japan" => println("日本")
case _ => println("我不认识!")
}