Let Scala infer simple expression types.

type-inference Scala can infer many local types from the value on the right side of an assignment.

Type Inference

count
TypeInference.scala
Replay: real traced execution (multi-file project)
object Main {
  def main(args: Array[String]): Unit = {
    val count = 4
    val doubled = count * 2
    val next: Int = count + 1
    val summary = "doubled=" + doubled

    println("count=" + count)
    println("next=" + next)
    println(summary)
  }
}
object Main {
  def main(args: Array[String]): Unit = {
    val count = 7
    val doubled = count * 2
    val next: Int = count + 1
    val summary = "doubled=" + doubled

    println("count=" + count)
    println("next=" + next)
    println(summary)
  }
}
  1. count ← 4, doubled ← 8, next ← 5, summary ← doubled=8

    1object Main {2  def main(args: Array[String]): Unit = {3    val count→ 4 = 4 //@count=74    val doubled→ 8 = count4 * 25    val next→ 5: Int = count4 + 16    val summary→ doubled=8 = "doubled=" + doubled878    println("count=" + count4)9    println("next=" + next5)10    println(summarydoubled=8)11  }12}
    outputcount=4
    next=5
    doubled=8
  1. count ← 7, doubled ← 14, next ← 8, summary ← doubled=14

    1object Main {2  def main(args: Array[String]): Unit = {3    val count→ 7 = 74    val doubled→ 14 = count7 * 25    val next→ 8: Int = count7 + 16    val summary→ doubled=14 = "doubled=" + doubled1478    println("count=" + count7)9    println("next=" + next8)10    println(summarydoubled=14)11  }12}
    outputcount=7
    next=8
    doubled=14

Follow the Values

  1. count starts at 4.
  2. next = count + 1 becomes 5.
  3. doubled = count * 2 becomes 8.
  4. summary is built from the doubled value.
  5. The program prints count=4, next=5, and doubled=8. | count | next | doubled | | --- | --- | --- | | 4 | 5 | 8 | | 7 | 8 | 14 |

Exercise: TypeInference.scala

Reproduce next=5 and doubled=8, then use count 7 to predict both values.