Can we use match to check the type of a class

Freewind picture Freewind · Mar 3, 2011 · Viewed 56.3k times · Source

I'm new to scala, and I'm learning the match keyword now.

I wanna know if we can use the keyword match to check the type of a class. My code is:

object Main {
    def main(args: Array[String]) {
        val x = "AA"
        checkType(x)
    }

    def checkType(cls: AnyRef) {
        cls match {
            case String => println("is a String")
            case Date => println("is a Date")
            case _ => println("others")
        }
    }
}

The code can't be compiled, so, it's impossible to do this? What is the scala-way to check the type of a class? Is it:

if(cls.isInstanceOf[String]) { ... }
else if(cls.isInstanceOf[Date]) { ... }
else { ... }

Right?

Answer

Wilfred Springer picture Wilfred Springer · Mar 3, 2011

This however will compile:

def checkType(cls: AnyRef) {                    
  cls match {                                 
    case s: String => println("is a String")
    case d: Date => println("is a Date")    
    case _ => println("others")             
  }                                                   
}

... or the simplified version of that:

def checkType(cls: AnyRef) =
  cls match {                                 
    case _: String => println("is a String")
    case _: Date => println("is a Date")    
    case _ => println("others")             
  }