Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - Calling a method with def parameter fails with 'Illegal class name"

Tags:

groovy

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)

like image 460
Jahg Daglet Avatar asked Apr 06 '16 19:04

Jahg Daglet


People also ask

What is def in Groovy script?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do you call a function in Groovy?

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: () .

What does it do in Groovy?

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.


1 Answers

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.

like image 141
Jérémie B Avatar answered Oct 21 '22 01:10

Jérémie B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!