0

I've a nullable field where I want to perform operation, if not null. return null otherwise. I can write it in plain Java as

return (myfield != null)? myfield.getData() :null;

How can I write the same code in one line with Optional

Something like below. Below code is not a correct code, just want to ask the correct version of it

return Optional.ofNullable(myfield).map(Functionas.identity().getData()).orElse(null);
ThrowableException
  • 1,168
  • 1
  • 8
  • 29
  • 2
    Why do you want to make long your way!? what is the benefit of usage optional here? go with the first solution. – Hadi J May 01 '20 at 16:17
  • @HadiJ Sure, Wasn't sure, if this will be long. that's why I asked.. – ThrowableException May 01 '20 at 16:22
  • 1
    see this, please. https://stackoverflow.com/questions/23454952/uses-for-optional – Hadi J May 01 '20 at 16:27
  • 1
    This is not the type of problem Optional was intended to solve rather using Optional here would be an *overkill*, *less memory friendly* and to some extent less readable via the Optional approach too. so conclusion is I'd stick with your approach of: `return myfield != null ? myfield.getData() : null;` as it's short and sweet and reads well. – Ousmane D. May 01 '20 at 16:48

0 Answers0