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.
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.
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")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With