-2

What is the best way to write something like this in shorthand using operators, if possible?

    if (l1 == null && l2 == null){
        return null;
    }
    else if (l1 == null){
        return l2;
    }
    else if (l2 == null){
        return l1;
    }

2 Answers2

1

For me, it's this:

return l1 == null ? l2 : l1;

If l1 & l2 are null, it will return null. Else, if at least one of them it not null, it will return the one that is defined.

Elikill58
  • 4,050
  • 24
  • 23
  • 45
0

For two variables it's probably overkill but a functional way of doing so can be:

return Optional(l1)
  .orElse(l2)
  .getOrElse(null);

Self-explanatory I believe.

Gaël J
  • 11,274
  • 4
  • 17
  • 32