Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure with typed arguments in Groovy

I'd like to be more explicit about my closures regarding their argument types. So I would write something like

List<Y> myCollect(List<X> list, Closure<X,Y> clos) { ... }

I know that Groovy won't use that type information, but Groovy++ may use it at compile time. Can this be be achieved (other than putting it into a comment)?

UPDATE: The title may sound misleading, but I thought the above example would make it clearer. I'm interested in specifying types of a closure which is the argument of some function. Suppose, I want to redefince the built-in collect. So I'm interested in writing myCollect, not in writing clos. What I want to achieve is get compile time errors

myCollect(['a', 'ab'], { it / 2 }) // compile error
myCollect(['a', 'ab'], { it.size() })  // OK 
like image 759
Adam Schmideg Avatar asked Apr 15 '11 19:04

Adam Schmideg


People also ask

What is the use of closure in Groovy?

A closure is an anonymous block of code. In Groovy, it is an instance of the Closure class. Closures can take 0 or more parameters and always return a value. Additionally, a closure may access surrounding variables outside its scope and use them — along with its local variables — during execution.

How do I return a value in Groovy?

The last line of a method in Groovy is automatically considered as the return statement. For this reason, an explicit return statement can be left out. To return a value that is not on the last line, the return statement has to be declared explicitly.

What is call method 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: () . This can be especially useful in for example a DSL written with Groovy.

What is closure in gradle?

Note in Gradle DSL, closures are frequently (and idiomatically) used as the last method parameter to configure some object. This is a pattern called configuration closure.


1 Answers

You can define the types of a closure's parameters, but the syntax shown above is incorrect. Here is a closure without parameter types:

def concatenate = {arg1, arg2 ->
  return arg1 + arg2
}

And here is the same closure with parameter types

def concatenate = {String arg1, String arg2 ->
  return arg1 + arg2
}

I know that Groovy won't use that type information, but Groovy++ may use it at compile time.

Groovy does do some compile-time type checking, but not as much as Groovy++ (or Java). Even if the type information is not used at compile-time it will be checked at runtime, and is also valuable as a form of documentation.

like image 140
Dónal Avatar answered Nov 09 '22 00:11

Dónal