考虑下面的代码:的try-catch,可选/空,拉姆达
- obj是不会被修改之后被intialised的服务,但是,由于try/catch块,它不被视为有效决赛。 有没有办法避免这种情况?
是否可选可能被认为是避免空检查的通用方法?在这个例子中,服务会抛出异常,或者返回null,或者总是返回Optional?
//to be used outside try/catch block, object must be initialized as null SomeObject obj = null; try { obj = someService.getSomeObject(); } catch (ServiceException e) { LOG.error("Something nasty happened", e); } //the service could have returned a null object if(obj == null) { LOG.error("Obj is null"); } //to be used in a lambda, object must be final SomeObject objCopy = obj; boolean test = someList.stream() .anyMatch(o->o.equals(objCopy));
'它不被认为是有效的最终'你是什么意思? – 2016-11-23 14:45:03
@LutzHorn,一个变量被认为是有效的最终的,如果它的值初始化后永远不会改变。 –