天天看点

null in ABAP and nullpointer in JavaABAPJava2B青年的写法文艺青年的写法

ABAP

Java

class Outer {
    Nested nested;
    Nested getNested() {
        return nested;
    }
    
    public Outer(){
        // nested = new Nested();
    }
}
class Nested {
    Inner inner;
    Inner getInner() {
        return inner;
    }
    
    public Nested() {
        // inner = new Inner();
    }
}

class Inner {
    String foo = "Jerry";
    String getFoo() {
        return foo;
    }
}           

为了打印嵌套层数很深的foo:

2B青年的写法

public void test1(){
        Outer outer = new Outer();
        if (outer != null && outer.nested != null && outer.nested.inner != null) {
            System.out.println(outer.nested.inner.foo);
        }
    }           

文艺青年的写法

public void test2(){
        Optional.of(new Outer()).map(Outer::getNested).map(Nested::getInner).map(Inner::getFoo)
            .ifPresent(System.out::println);
    }           

More discussion of ABAP, Java and JavaScript could be found from my Wechat article

Jerry的ABAP, Java和JavaScript乱炖

本文来自云栖社区合作伙伴“汪子熙”,了解相关信息可以关注微信公众号"汪子熙"。