如何检查对象以查看其类型并返回Casted对象

编程入门 行业动态 更新时间:2024-10-11 23:22:08
本文介绍了如何检查对象以查看其类型并返回Casted对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个方法,我通过一个对象。在这种方法,我检查它的类型,并根据类型我做的东西,并返回一个长。我试过了每一种方式,我可以想到这样做,我总是得到几个编译器错误告诉我它期望一个特定的对象,但另一个。有人可以向我解释我做错了,指导我在正确的方向?我到目前为止的尝试如下:

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:

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

推荐答案

模式匹配会让它更好。

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 }

更多推荐

如何检查对象以查看其类型并返回Casted对象

本文发布于:2023-08-04 21:46:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1299884.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   看其   类型   Casted

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!