Type Parameters and Generics
Generic Choice
Choose between two fields of the same generic type.
Generic Choice
GenericChoice.scala
case class Choice[A](first: A, second: A)
object Main {
def main(args: Array[String]): Unit = {
val preferFirst =
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 =
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)
}
}
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.