主构造器:
Visibility | Accessor? | Mutator? |
---|---|---|
var | 是 | 是 |
val | 是 | 否 |
no var or val | 否 | 否 |
Adding the private keyword to var or val | 否 | 否 |
在类里面,无论上述条件如何,都可以访问和修改
Case classes
默认什么都不加的话是val,例如:
case class Person(name: String)
scala> val p = Person(“Dale Cooper”)
p: Person = Person(Dale Cooper)
scala> p.name
res0: String = Dale Cooper
构造器
尽量少写辅助构造器,用默认值代替,例如:
class Pizza(
var crustSize: CrustSize = Pizza.DefaultCrustSize,
var crustType: CrustType = Pizza.DefaultCrustType
):
override def toString =
s"A $crustSize pizza with a $crustType crust"
在case class中加辅助构造器,只要加aplly方法,例如:
case class Person(var name: String, var age: Int)
object Person:
def apply() = new Person("", 0) // zero-args constructor
def apply(name: String) = new Person(name, 0) // one-arg constructor
val a = Person() // Person(,0)
val b = Person(“Sarah Bracknell”) // Person(Sarah Bracknell,0)
val c = Person(“Sarah Bracknell”, 32) // Person(Sarah Bracknell,32)
a.name = “Sarah Bannerman”
a.age = 38
println(a) // Person(Sarah Bannerman,38)
枚举
object Margin extends Enumeration {
type Margin = Value
val TOP, BOTTOM, LEFT, RIGHT = Value
}
object Main extends App {
import com.acme.app.Margin._
// use an enumeration value in a test
var currentMargin = TOP
// later in the code …
if (currentMargin == TOP) println(“working on Top”)
// print all the enumeration values
import com.acme.app.Margin
Margin.values foreach println
}
下面这种方法也是创建美剧方式但是太啰嗦不推荐
package com.acme.app {
trait Margin
case object TOP extends Margin
case object RIGHT extends Margin
case object BOTTOM extends Margin
case object LEFT extends Margin
}