4

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?

TeaCupApp
  • 11,316
  • 18
  • 70
  • 150

3 Answers3

4

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.

Judge Mental
  • 5,209
  • 17
  • 22
3

x++ is essentially equivalent to x = x + 1, which doesn't make sense in your case:

mrq.getId() = mrq.getId() + 1
blahdiblah
  • 33,069
  • 21
  • 98
  • 152
1

++ operator is used to increment the value of variable by 1. so a++ is treated as a=a+1. That means the operand on which it is used will be where the assignment will be done.

When you write mrq.getId()++ it doesn't provide you an operand variable which it can increment and hence this doesn't work.

Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63