我们可以使用match检查类的类型吗 [英] Can we use match to check the type of a class
本文介绍了我们可以使用match检查类的类型吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是scala的新手,现在正在学习match
关键字.
I'm new to scala, and I'm learning the match
keyword now.
我想知道我们是否可以使用关键字match
来检查类的类型.我的代码是:
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")
}
}
}
代码无法编译,因此,这不可能吗?检查班级类型的scala方式是什么?是吗?
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 { ... }
对吗?
推荐答案
但是 会编译:
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")
}
这篇关于我们可以使用match检查类的类型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文