Type Parameters and Generics
Generic Box Value
Store one value in a class with a type parameter.
generic-class
A class can take a type parameter too. `Box[A]` stores one value while keeping the value's type known to the compiler.
Generic Box Value
GenericBoxValue.scala
Replay: real traced execution (multi-file project)
case class Box[A](value: A)
object Main {
def main(args: Array[String]): Unit = {
val points = 12
val box = Box[Int](points)
val doubled = box.value * 2
println("value=" + box.value)
println("doubled=" + doubled)
}
}
case class Box[A](value: A)
object Main {
def main(args: Array[String]): Unit = {
val points = 5
val box = Box[Int](points)
val doubled = box.value * 2
println("value=" + box.value)
println("doubled=" + doubled)
}
}
case class Box[A](value: A)
object Main {
def main(args: Array[String]): Unit = {
val points = 20
val box = Box[Int](points)
val doubled = box.value * 2
println("value=" + box.value)
println("doubled=" + doubled)
}
}
points ← 12, box ← Box(12), doubled ← 24
3object Main {4 def main(args: Array[String]): Unit = {5 val points→ 12 = 12 //@points=5, 206 val box→ Box(12) = Box[Int](points12)7 val doubled→ 24 = boxBox(12).value * 289 println("value=" + box.value12)10 println("doubled=" + doubled24)11 }12}outputvalue=12 doubled=24
points ← 5, box ← Box(5), doubled ← 10
3object Main {4 def main(args: Array[String]): Unit = {5 val points→ 5 = 56 val box→ Box(5) = Box[Int](points5)7 val doubled→ 10 = boxBox(5).value * 289 println("value=" + box.value5)10 println("doubled=" + doubled10)11 }12}outputvalue=5 doubled=10
points ← 20, box ← Box(20), doubled ← 40
3object Main {4 def main(args: Array[String]): Unit = {5 val points→ 20 = 206 val box→ Box(20) = Box[Int](points20)7 val doubled→ 40 = boxBox(20).value * 289 println("value=" + box.value20)10 println("doubled=" + doubled40)11 }12}outputvalue=20 doubled=40