我们可以使用 match 来检查类的类型吗

2024-01-04

我是 scala 新手,我正在学习match现在关键字。

我想知道我们是否可以使用关键字match检查类的类型。我的代码是:

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

代码无法编译,所以,这是不可能的吗?检查类类型的 scala 方法是什么?是吗:

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

Right?


然而这will编译:

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

...或者其简化版本:

def checkType(cls: AnyRef) =
  cls match {                                 
    case _: String => println("is a String")
    case _: Date => println("is a Date")    
    case _ => println("others")             
  }                                                   
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我们可以使用 match 来检查类的类型吗 的相关文章

随机推荐