1

Is there a shortcut to the following statement?

if(b!=null) a=b;

The best I can come up with is

a=b??a;

I want to assign b to a only if b is not null, otherwise I want to leave a unchanged.

The statement a??=b; is the opposite of what I want, equivalent to

if(a==null) a=b;
programagor
  • 288
  • 4
  • 12
  • 4
    `a=b??a` seems concise enough for me - i don't think getting any shorter would provide any benefit at all. but to answer your question: no. – Franz Gleichmann Jan 31 '21 at 22:44
  • Isn't `a=b??a` already a shortcut? – Rno Jan 31 '21 at 22:51
  • The "shortcut" involves calling `a`'s setter and possibly getter regardless of `b`'s `null`ness. Ideally only the setter would be called, and only when `b` is actually null. – programagor Jan 31 '21 at 22:59
  • if your getters and setters have side-effects that could break something, then you shouldn't worry about whether or not they get called, but about fixing them. – Franz Gleichmann Feb 01 '21 at 05:58
  • @FranzGleichmann They could simply involve heavy IO which I would like to avoid, not necessarily side effects. – programagor Feb 02 '21 at 22:24
  • @programagor then i would say it's the task of the _getters and setters_ to check whether they have to do heavy lifting or not. just my two cents. – Franz Gleichmann Feb 02 '21 at 22:29

0 Answers0