##define class // default public class Counter {
private var value = 0 def increment() {value += 1} def current() = value}
##using class val myCounter = new Counter myCounter.increment() println(myCounter.current) // you can ignore the bracket if the method of instance is not side effect
##getter and setter which is generated to field val/var name public name/ name_= ( for var)
@BeanProperty val/var name public name / getName() / name_= (for var) / setName(..) (for var)
private val/name private name / name_= (for var)
private[this] val/var name -
private[class name] val/var name dependents on implementation
auxiliary constructor
class Person { private var name = "" private age = 0 def this(name: String){ this() // call primary constructor this.name = name } def this(name: String, age: Int) { // another auxiliary constructor this(name) this.age = age }}val p1 = new Person // call primary constructorval p2 = new Person("name") // call auxiliary constructorval p3 = new Person("Fred", 32) // call auxiliary constructor
primary constructor
class Person(val name: String, val age: Int){ //primary contructor will execute all code that are included in this scope}//above equals java code:public class Person{ private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } //getter... //setter...}
##getter and setter which is generated to primary constructor scala's getter is "name" and setter is "name_=(...)"
java's getter is "getName()" and setter is "setName(..)"
name: String private object field. It'll be not exists if it isn't used.
private val/var name: String private field, private setter and getter method
val/var name: String private field, public setter and getter method
@BeanProperty val/var name: String private field, public scala/java setter and getter method
inner class
import scala.collection.mutable.ArrayBufferclass Network { class Member(val name: String){ val contacts = new ArrayBuffer[Member] } private val members = new ArrayBuffer[Member] def join(name: String) = { val m = new Member(name) members += m m } }val chatter = new Networkval myFace = new Networkval fred = chatter.join("Fred") // the type of fred is chatter.Memberval wilma = chatter.join("wilma") fred.contacts += wilmaval barney = myFace.join("Barney") // the type of barney is myFace.Memberfred.contacts += barney // invalid cause the type of fred and barney is differents