Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 260
TeaCupApp Avatar asked Feb 20 '23 17:02

TeaCupApp


2 Answers

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.

like image 166
Judge Mental Avatar answered Mar 13 '23 07:03

Judge Mental


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

mrq.getId() = mrq.getId() + 1
like image 29
blahdiblah Avatar answered Mar 13 '23 08:03

blahdiblah