Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use match to check the type of a class

People also ask

How do you match a pattern in Scala?

A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.

Which method of case class allows using objects in pattern matching?

Case classes are Scala's way to allow pattern matching on objects without requiring a large amount of boilerplate. In the common case, all you need to do is add a single case keyword to each class that you want to be pattern matchable.

What is the default option in a match case in Scala?

getList("instance").


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")             
  }                                                   

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")
        }
    }
}