I am hoping to get an explanation as to why the call to this Groovy method works as expected:
def f1(int n) {
return n + 1
}
println f1(1) // -> 2
But, if the parameter is not specifically defined ("def n" instead of "int n"), the method call needs to change:
def f2(def n) {
return n + 1
}
println f2(1) // Exception: Illegal class name
println this.&f2(1) // -> 2
What is happening under the hood to make this necessary?
UPDATED with more info:
This is on Windows with Groovy 2.4.5 JVM 1.8.0_51
The entire script is those 9 lines in a file called 1.groovy - nothing else.
I am running this from the console (cmdr) using "groovy 1.groovy"
The error on line 8 is:
Caught: java.lang.ClassFormatError: Illegal class name "3$f2" in class file 3$f2 java.lang.ClassFormatError: Illegal class name "3$f2" in class file 3$f2 at 3.run(3.groovy:8)
The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () .
it is an implicit variable that is provided in closures. It's available when the closure doesn't have an explicitly declared parameter. When the closure is used with collection methods, such as removeIf , it will point to the current iteration item.
This is related to the name of your Script. When you have a file "1.groovy", Groovy generate a class with the name "1" in the default package, which is not a valid class name.
When you use f2(n)
without a type, as this method is "too generic", Groovy try to find a matching method, or a class named f2
, or an inner class named f2 : loading an inner class f2
of the class 1
fail, because the name is invalid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With