【发布时间】:2013-07-14 22:14:29
【问题描述】:
当我尝试将 Any 与字符串匹配时,我没有得到正确的输出。我的代码如下:
def typecast(cls: Any) {
cls match {
case s: String => println("string")
case d: Double => println("double")
case i: Int => println("int")
case o: Option[_] => println("option")
case _ => println("nothing")
}
}
如果cls 的类型为Double 或Int,则匹配正确的大小写,但匹配String 或Option[_] 类型的大小写_ (println("nothing"))。
任何想法为什么这不起作用或我做错了什么?提前致谢!
编辑: 如果我这样做,它可以正常工作,例如typecast("foo") 或 typecast(Some("foo")),但在我的情况下,cls 的接收值如下:
val cls: Any = classOf[User].getDeclaredField("name")
字段可以是String 或Option[String]
【问题讨论】:
-
对我来说就像一个魅力,typecast("foo") 打印“string”,typecast(None) 和 typecast(Some("stuff")) 打印“option”。
-
刚刚认识到,这只是在我的特殊情况下发生。我编辑了这个问题。感谢您的提示。
标签: scala