Executing the below code
println("Pattern Matching by type")
val priceofCar : Any = 2.0
val priceType = priceofCar match{
case price: Int => "Int" // 1
case price: Float => "Float" // 2
case price: Any => "Any" // 3
case price: Double => "Double" // 4
case _ => "others" // 5
}
// println(:type priceofCar)
println(s"Car price type = $priceType")
ends up with the below output
Car price type = Any
and a warning message
warning: unreachable code
case price: Double => "Double" // 4
^
one warning found.
But, after swapping the order of rows //3 and //4, no warnings are shown and get the below output
Car price type = Double
Now my doubt is,
val priceType = priceofCar match{
case price: Int => "Int" // 1
case price: Float => "Float" // 2
case price: Any => "Any" // 3
case price: Double => "Double" // 4
case _ => "others" // 5
}
The pattern matching is sequential for match which means it will first match price with 1st case which is price: Int then Float then Any and so on.
We should keep the most specific type first, As we can see in the diagram that Any is at the top of type hierachy (most generic type) it can consume anything that's the reason you are getting the warning useless code for lines after case price: Any
if you see in line 5 it says case price of type any which is on the top of hireachy of the types. It will match anything Int, Flot, String, List, or any user define data type. that's why the lines below case price:Any are useless because the control is not going to the next case after Any.
case price: Any
match with anything including Double
so if it before case price: Double
later is newer matched.
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