Why can Groovy constants be increased?

The Groovy Console ++(++(++(++1++)++)++)++is rated as 5!
Why ?
I would expect errors that literal constants cannot be incremented !

Pre-Increment gives the next Integer, while Post-Increment gives the same Integer, but I would expect both to throw errors when used with literal constants.

[[I am running this on Windows 10 with Groovy 2.4.10 with Java 1.8.0_101]]

+6
source share
1 answer

Good question, I would like to receive an authoritative answer.

, . , , ​​ Groovy ( ), , , (, ).

: , , , -, .

Groovy , .

  • if (condition) int foo=1 javac: " ", , , , ? Groovy.

  • private .

  • final . final int. 2.5, , . .

final Groovy 2,4 2,5:

$ ./groovy-2.4.11/bin/groovy -e "final j=0; println(++j)"
1
$ ./groovy-2.5.0-alpha-1/bin/groovy -e "final j=0; println(++j)"
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
script_from_command_line: 1: The variable [j] is declared final but is reassigned
. At [1:20]  @ line 1, column 20.
   final j=0; println(++j)
                      ^
1 error

, Groovy 2.5 - :

$ ./groovy-2.4.11/bin/groovy -e "println(++1)"
2
$ ./groovy-2.5.0-alpha-1/bin/groovy -e "println(++1)"
2

, ++1?

, Groovy - Java, Java. -. ++ Groovy Java.

Groovy 9 (. org. codehaus.groovy.control.CompilePhase): , , , , , , , , .

GroovyConsole. :

def foo() {
    ++1
}

, - :

public java.lang.Object foo() {
    ++(1)
}

. . , ++(2+2) 5. ... , ++ - , incrementThis(thing), , , , 1 .

IDE, ctrl-click ++, org.codehaus.groovy.runtime.DefaultGroovyMethods.next(Number self):

/**
 * Increment a Number by one.
 *
 * @param self a Number
 * @return an incremented Number
 * @since 1.0
 */
public static Number next(Number self) {
    return NumberNumberPlus.plus(self, ONE);
}

, , self + ONE, , self, , . , ++(x) - DefaultGroovyMethods.next(x), .

, , , javac groovyc :

//Wat.java:
public class Wat {
    public int foo() {
        int i=1;
        return ++i;
    }
}

//wat.groovy:
def foo() {
  ++1
}

(Java 1.8, Groovy 2.4, ):

// Java:
0: iconst_1                // load int value 1 onto stack
1: istore_1                // store int value into variable #1
2: iinc          1, 1      // increment local variable #1 by 1
5: iload_1                 // load int value from local variable #1
6: ireturn                 // return that integer value

// Groovy:
43: iconst_1               // load int value 1 onto stack
44: iconst_1               // load another int value 1 onto stack
45: iadd                   // add those 2 ints (result stored on stack in place of first int, stack is popped by 1)
46: invokestatic  #58      // Invoke method java/lang/Integer.valueOf(previous result)
49: areturn                // Return that new Integer result

Groovy ++1 Integer.valueOf(1+1) ( ).

def foo(i) { ++i }? , i, , Object, -, DefaultGroovyMethods.next NumberNumberPlus.plus. , , , .

+7
source

Source: https://habr.com/ru/post/1017354/