scala 如何检查对象以查看其类型并返回强制转换的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2659311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Can I Check an Object to See its Type and Return A Casted Object
提问by Russ Bradberry
I have method to which I pass an object. In this method I check it's type and depending on the type I do something with it and return a Long. I have tried every which way I can think of to do this and I always get several compiler errors telling me it expects a certain object but gets another. Can someone please explain to me what I am doing wrong and guide me in the right direction? What I have tried thus far is below:
我有传递对象的方法。在这种方法中,我检查它的类型,并根据类型对它进行处理并返回一个 Long。我已经尝试了所有我能想到的方法来做到这一点,但我总是收到几个编译器错误,告诉我它期望某个对象但得到另一个对象。有人可以向我解释我做错了什么并指导我朝着正确的方向前进吗?到目前为止我尝试过的内容如下:
override def getInteger(obj:Object) = {
if (obj.isInstanceOf[Object]) null
else if (obj.isInstanceOf[Number])
(obj:Number).longValue()
else if (obj.isInstanceOf[Boolean])
if (obj:Boolean) 1 else 0
else if (obj.isInstanceOf[String])
if ((obj:String).length == 0 | (obj:String) == "null")
null
else
try {
Long.parse(obj:String)
} catch {
case e: Exception => throw new ValueConverterException("value \"" + obj.toString() + "\" of type " + obj.getClass().getName() + " is not convertible to Long")
}
}
回答by missingfaktor
Pattern matching would make it much more nicer.
模式匹配会让它变得更好。
def getInteger(obj: Any) = obj match {
case n: Number => n.longValue
case b: Boolean => if(b) 1 else 0
case s: String if s.length != 0 && s != "null" => s.toLong
case _ => null
}
回答by Randall Schulz
This code cries out for using a match:
这段代码要求使用匹配:
obj match {
case n: Number => n.longValue
case b: Boolean => if (b) 1 else 0
case s: String => if ((s eq null) || s.length == 0) null else {
// try ... catch ... etc.
}
case o: Object => null
}
Followed my own advice from my comment to my original reply...
按照我自己的建议从我的评论到我的原始回复...
回答by user unknown
This might be a start:
这可能是一个开始:
def getInteger (o : Any) : Long = o match {
case (o: Boolean) => if (o) 1 else 0
case (l: Long) => l
case (s: String) => java.lang.Long.parseLong (s)
case _ => 0L
}
(I don't have something to override, and skipped the try/catch for brevity)
(我没有要覆盖的东西,为了简洁跳过了 try/catch)

