Change object state through a method.

fields-methods Fields store object state. Methods read or update that state through named behavior.

Fields and Methods

start
FieldsMethods.scala
Replay: real traced execution (multi-file project)
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 = 1
    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 = 3
    val counter = new Counter(start)
    val after = counter.add(2)

    println("start=" + start)
    println("after=" + after)
    println("current=" + counter.value)
  }
}
  1. start ← 1, counter ← [counter]

    12object Main {13  def main(args: Array[String]): Unit = {14    val start→ 1 = 1 //@start=315    val counter→ [counter] = new Counter(start1)16    val after = counter[counter].add(2)1718    println("start=" + start)
  2. def add(step: Int): Int =

    4def add(step2: Int): Int = {5  value = value1 + step26  value7}
  3. after ← 3

    15    val counter = new Counter(start)16    val after→ 3 = counter[counter].add(2)1718    println("start=" + start1)19    println("after=" + after3)20    println("current=" + counter.value3)21  }22}
    outputstart=1
    after=3
    current=3
  1. start ← 3, counter ← [counter]

    12object Main {13  def main(args: Array[String]): Unit = {14    val start→ 3 = 315    val counter→ [counter] = new Counter(start3)16    val after = counter[counter].add(2)1718    println("start=" + start)
  2. def add(step: Int): Int =

    4def add(step2: Int): Int = {5  value = value3 + step26  value7}
  3. after ← 5

    15    val counter = new Counter(start)16    val after→ 5 = counter[counter].add(2)1718    println("start=" + start3)19    println("after=" + after5)20    println("current=" + counter.value5)21  }22}
    outputstart=3
    after=5
    current=5