Here is my code. I got a compile error at second case clause:
Error:(92, 26) value < is not a member of AnyVal case x if x._2 < 2 => "price under 2"
def tupleMatch: Unit = {
val donut = Tuple2("Donut", 2.5)
val plain = Tuple2("Plain", 1.0)
val tuples = List(donut, plain)
tuples.foreach { tuple =>
val toPrint = tuple match {
case ("Donut", price) => s"price of Donut is ${donut._2}"
case (_, price) if price < 2 => "price under 2"
case _ => "other"
}
println(toPrint)
}
}
After I change
val plain = Tuple2("Plain", 1)
to
val plain = Tuple2("Plain", 1.0)
it finally works. It makes me confusing, I want to know why?
That is because your tuples array is formed by two different types: Tuple2[String, Int]
and Tuple2[String, Double]
. These types are inferred by the compiler and the interfered type of tuples array is then Tuple2[String, AnyVal]
. When you put a Double representation the compiler is capable of create the Tuple2[String, Double]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With