##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 constructor
val p2 = new Person("name") // call auxiliary constructor
val 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.ArrayBuffer
class 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 Network
val myFace = new Network
val fred = chatter.join("Fred") // the type of fred is chatter.Member
val wilma = chatter.join("wilma")
fred.contacts += wilma
val barney = myFace.join("Barney") // the type of barney is myFace.Member
fred.contacts += barney // invalid cause the type of fred and barney is differents