Reputation: 654
I found the below code.
val carType = "SUV"
val space = carType match{
case car if(car.contains("SUV") || car.contains("sports")) => "limited"
case "sedan" => "family car"
case _ => "vehicle"
}
println(s"4 Space of $carType is $space")
Trying to understand from where came the word 'car' in the first case statement ? Is it a variable ? if so it is nowhere declared nor initialised? Can someone clarify this?
Upvotes: 1
Views: 92
Reputation: 7297
It's bound to the matching value for the purpose of using it in the qualifying if statement. The first case is when it contains SUV or sports, but it isn't exactly matching as in the second case ("sedan"). You need something to call 'contains' on, here it's 'car'.
You could change it to x or anything else and it would behave the same.
The if statement is called a "guard". https://docs.scala-lang.org/tour/pattern-matching.html
Upvotes: 5