0
case class Thing(n: Int)
def ThingCreator(c:Int): Thing = 
{
    val a = 10
    val b = 20
    c match {
        case 0 => Thing(1)
        case a => Thing(2)
        case b => Thing(3)
        case _ => Thing(4)
    }
}

What would be the output if we call ThingCreator() with inputs ranging from 0 to 100?

The answer was given as Thing(1) and Thing(2) but I don't get how it is not Thing(1) through Thing(4). If we pass 50 it should match the last case. Can someone explain how it works?

blor
  • 25
  • 5
  • for **lowercase** in **pattern match**, it means it's a variable, you should use ``a`` for match the value. – chengpohi Mar 01 '18 at 08:42

2 Answers2

0

case x, where x is any lowercase identifier, matches any value and assigns it to a newly created variable named x.

This is true regardless of whether or not a variable with the same name already exists.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0

Thats becuase Scala compiler will never go below the case a => Thing(2) line in your match case pattern

Scala compiler should throw a warning

patterns after a variable pattern cannot match (SLS 8.1.1)
    case a => Thing(2)
         ^

and

unreachable code
case b => Thing(3)
               ^

And SLS 8.1.1 states

A variable pattern x is a simple identifier which starts with a lower case letter. It matches any value, and binds the variable name to that value. The type of x is the expected type of the pattern as given from outside. A special case is the wild-card pattern _ which is treated as if it was a fresh variable on each occurrence.

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97