58

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?

Simón
  • 456
  • 8
  • 23
Freewind
  • 193,756
  • 157
  • 432
  • 708

2 Answers2

98

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")             
  }                                                   
Wilfred Springer
  • 10,869
  • 4
  • 55
  • 69
  • 13
    or, **even** simpler: since match yields a value, is to put the `println(...)` around it and have the cases resolve to the appropriate strings. – Carl May 09 '13 at 19:24
15

You need a identifier before the type annotation in case statement.

Try this and it should work:

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

    def checkType(cls: AnyRef) {
        cls match {
            case x: String => println("is a String:"+ x)
            case x: Date => println("is a Date:" + x)
            case _ => println("others")
        }
    }
}
Brian Hsu
  • 8,781
  • 3
  • 47
  • 59
  • 1
    I like this answer, as it's impossible to do anything with the checked value inside the case clauses (in this snippet 'cls') unless it is given a name other than the special _. In many cases you'd want to take action on the object based on its type and this answer is well geared towards that use case. For as much as it matters... – matanster Mar 27 '13 at 17:39