Podemos usar match para comprobar el tipo de una clase
Soy nuevo en scala y ahora estoy aprendiendo la palabra clave match
.
Quiero saber si podemos usar la palabra clave match
para comprobar el tipo de una clase. Mi código es:
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")
}
}
}
El código no se puede compilar, así que, ¿es imposible hacer esto? ¿Cuál es la forma de scala de verificar el tipo de clase? Es:
if(cls.isInstanceOf[String]) { ... }
else if(cls.isInstanceOf[Date]) { ... }
else { ... }
¿Correcto?
41
2 answers
Esto sin embargo compilará:
def checkType(cls: AnyRef) {
cls match {
case s: String => println("is a String")
case d: Date => println("is a Date")
case _ => println("others")
}
}
... o la versión simplificada de eso:
def checkType(cls: AnyRef) =
cls match {
case _: String => println("is a String")
case _: Date => println("is a Date")
case _ => println("others")
}
75
Author: Wilfred Springer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-03 06:01:59
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-03 06:01:59
Necesita un identificador antes de la anotación de tipo en la instrucción case
.
Prueba esto y debería funcionar:
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")
}
}
}
11
Author: Brian Hsu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-03 06:02:40
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-03 06:02:40