0
votes

Pattern matching is not working as per the understanding.

I read the pattern matching concepts in the text book "Programming in Scala".

I have a pattern matching definition as below.

def checkMe (a:Any) =  a match {
      case Int => "I am an Integer"
      case Double => "I am a Double"
      case Char => "I am a Charecter"
      case _ => "I am something else"
     }

Irregardless whatever I pass while calling to the function, always the default case is executed.

E.g: checkMa(100) gives "I am something else" checkMe(10.) too gives "I am something else" etc..

Can someone please help me understand what is wrong in the definition.

I expect the definition executing according to the type I pass.

2

2 Answers

6
votes

The reason is that you are matching against the companion object (Int, Double, Char) instead of the actual type, a solution is to match against the type like this:

def checkMe (a:Any) =  a match {
  case _: Int => "I am an Integer"
  case _: Double => "I am a Double"
  case _: Char => "I am a Charecter"
  case _ => "I am something else"
}

Then, you can test in a REPL to see the expected results:

@ checkMe(4) 
res3: String = "I am an Integer"

@ checkMe(4.0) 
res4: String = "I am a Double"

@ checkMe('a') 
res5: String = "I am a Charecter"

@ checkMe("Asdas") 
res6: String = "I am something else"
4
votes

you need a variable: Type to pattern match,

  def checkMe(a: Any) = a match {
    case a: Int => "I am an Integer"
    case a: Double => "I am a Double"
    case a: Char => "I am a Charecter"
    case _ => "I am something else"
  }

example - https://scastie.scala-lang.org/prayagupd/Pxzn4w8GQGCMIub33xMrRg/1