groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dinko Srko─Ź <>
Subject Re: Emulating method overloading with closures?
Date Wed, 15 Apr 2015 07:46:23 GMT
Parameters with default values is a good solution. There is another
one, perhaps less elegant, but more flexible. It can be used in places
where default values cannot help e.g. where the types of parameters

  def foo = new Closure(null) {
      String doCall(int arg1, String arg2) { arg1 + arg2 }
      int doCall(int arg1, int arg2) { arg1 + arg2 }

  assert foo(42, 'bar') == '42bar'
  assert foo(40, 2) == 42


On 15 April 2015 at 03:25, Keith Suderman <> wrote:
> You can specify default values for parameters in Groovy, so you should be able to achieve
what you want with
> def foo = {String args, boolean x, boolean y, boolean z=true -> ... }
> foo("bar", true, true)
> foo("bar", true, true, false)
> Keith
> On Apr 14, 2015, at 8:19 PM, Henrik Martin <> wrote:
>> Hi. I have a Groovy method that is overloaded, and I'm trying to achieve something
similar with closures. The methods look something like this:
>> int foo(String args, boolean x, boolean y) { ... }
>> int foo(String args, boolean x, boolean y, boolean z) { ... }
>> The first method basically just forwards to the overloaded version, passing a 'z'
argument with a default value. Is there any way I can convert these two methods to two closures
in the same class in a similar fashion as method overloading? The problem I run into seems
to be that closures are object instances, so I can't really have two closures with the same
name in the same class. Maybe using closures isn't appropriate in this case? What would be
a "Groovier way" of doing this? The reason I tried the closure approach is the "method as
an object instance" paradigm fits pretty well with the particular project I'm working on.
But I'm sure there's a better way of doing this...
>> Thanks,
>> -H
> ------------------------------
> Research Associate
> Department of Computer Science
> Vassar College
> Poughkeepsie, NY

View raw message