Classes and Objects
Fields and Methods
Change object state through a method.
Fields and Methods
FieldsMethods.scala
class Counter(start: Int) {
var value = start
def add(step: Int): Int = {
value = value + step
value
}
override def toString: String = "[counter]"
}
object Main {
def main(args: Array[String]): Unit = {
val start =
val counter = new Counter(start)
val after = counter.add(2)
println("start=" + start)
println("after=" + after)
println("current=" + counter.value)
}
}
class Counter(start: Int) {
var value = start
def add(step: Int): Int = {
value = value + step
value
}
override def toString: String = "[counter]"
}
object Main {
def main(args: Array[String]): Unit = {
val start =
val counter = new Counter(start)
val after = counter.add(2)
println("start=" + start)
println("after=" + after)
println("current=" + counter.value)
}
}
fields-methods
Fields store object state. Methods read or update that state through named behavior.