Can we use match to check the type of a class

前端 未结 2 1879
感动是毒
感动是毒 2021-02-01 12:32

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

相关标签:
2条回答
  • 2021-02-01 12:57

    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")
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-01 13:14

    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")             
      }                                                   
    
    0 讨论(0)
提交回复
热议问题