Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unreachable code in Scala Pattern Matching

Tags:

scala

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,

  1. either it should stick to "Double" or "Any" in both cases, but not why ?
  2. why the warning is thrown ?
like image 224
luckyluke Avatar asked Sep 01 '25 00:09

luckyluke


2 Answers

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.

enter image description here

like image 190
Raman Mishra Avatar answered Sep 02 '25 16:09

Raman Mishra


case price: Any match with anything including Double so if it before case price: Double later is newer matched.

like image 20
talex Avatar answered Sep 02 '25 16:09

talex