Search code examples
javaoperatorsintsetteroperation

Why it is not possible to increment and then pass the value in set method by ++


I have a line of code that works like this,

mrq.setId((mrq.getId()+1));

But, When I tried to write it like this,

mrq.setId((mrq.getId()++));

It doesn't work, The error is, Invalid argument ot the operation ++/--

What is the technical reason behind it?


Solution

  • The increment operator requires a field or variable. Evaluating getId() doesn't result in an id field; it returns a copy of the value getId() returns (by "copy" I mean a literal copy for primitive types and a new reference for reference types). getId() might be implemented as return id; internally, but you don't get back the field id, only a copy of its value.

    The closest equivalent would be int i = getId(); setId( getId() + 1 ); return i;, but you're asking a lot to allow getId()++ as syntactic sugar for such an expression.