Type Parameters and Generics
Generic Choice
Choose between two fields of the same generic type.
same-generic-type
Both fields in `Choice[A]` use the same type parameter, so selecting either field produces the same result type. The example prints scalar properties of the selected value.
Generic Choice
GenericChoice.scala
Replay: real traced execution (multi-file project)
case class Choice[A](first: A, second: A)
object Main {
def main(args: Array[String]): Unit = {
val preferFirst = true
val first = "fast"
val second = "safe"
val choice = Choice[String](first, second)
val selected = if (preferFirst) choice.first else choice.second
val length = selected.length
println("selected=" + selected)
println("length=" + length)
}
}
case class Choice[A](first: A, second: A)
object Main {
def main(args: Array[String]): Unit = {
val preferFirst = false
val first = "fast"
val second = "safe"
val choice = Choice[String](first, second)
val selected = if (preferFirst) choice.first else choice.second
val length = selected.length
println("selected=" + selected)
println("length=" + length)
}
}
preferFirst ← true, first ← fast, second ← safe, choice ← Choice(fast,safe)
3object Main {4 def main(args: Array[String]): Unit = {5 val preferFirst→ true = true //@preferFirst=false6 val first→ fast = "fast"7 val second→ safe = "safe"8 val choice→ Choice(fast,safe) = Choice[String](firstfast, secondsafe)9 val selected→ fast = if (preferFirsttrue) choice.firstfast else choice.secondsafe10 val length→ 4 = selected.length→ 41112 println("selected=" + selectedfast)13 println("length=" + length4)14 }15}outputselected=fast length=4
preferFirst ← false, first ← fast, second ← safe, choice ← Choice(fast,safe)
3object Main {4 def main(args: Array[String]): Unit = {5 val preferFirst→ false = false6 val first→ fast = "fast"7 val second→ safe = "safe"8 val choice→ Choice(fast,safe) = Choice[String](firstfast, secondsafe)9 val selected→ safe = if (preferFirstfalse) choice.firstfast else choice.secondsafe10 val length→ 4 = selected.length→ 41112 println("selected=" + selectedsafe)13 println("length=" + length4)14 }15}outputselected=safe length=4