Groovy:方法的模糊方法重载

时间:2016-10-25 00:49:54

标签: groovy lambda closures

我在groovy-2.4.7中遇到public class App { void get(String pattern, NoArg handler) { ... } void get(String pattern, OneArg handler) { ... } void get(String pattern, TwoArg handler) { ... } } 异常。

我有3个功能界面:

{
  get("/", () -> "OK");
  get("/", req -> "OK");
  get("/", (req, rsp) -> rsp.send("OK"));
}

有一个App.java提供了一些Ambiguous method overloading for method方法,如:

{
   get("/", {-> "OK"})
}

从Java我可以拨打电话:

21:34:13.502 [ERROR] [system.err] groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method app.App#get.
21:34:13.502 [ERROR] [system.err] Cannot resolve which method to invoke for [class java.lang.String, class app.App$_closure1] due to overlapping prototypes between:
21:34:13.502 [ERROR] [system.err]   [class java.lang.String, interface app.NoArg]
21:34:13.502 [ERROR] [system.err]   [class java.lang.String, interface app.OneArg]
21:34:13.502 [ERROR] [system.err]   [class java.lang.String, interface app.TwoArg]

它在Java中完美运行,但是当我尝试时,我在Groovy中得到了{{1}}:

{{1}}

这是完整的堆栈跟踪:

{{1}}

我错过了什么吗?或者Groovy不支持这个?

感谢。

2 个答案:

答案 0 :(得分:3)

您需要将其强制转换为NoArg没有隐式转换为接口(与Java lambdas一样)

示例:

class Request{}

class Response{}

interface NoArg {
   Object handle();
}
interface OneArg {
   Object handle(Request req);
}
interface TwoArg {
   Object handle(Request req, Response rsp);
}

public class App {
  void get(String pattern, NoArg handler) {
    println(handler.handle())
  }
  void get(String pattern, OneArg handler) {
    println(handler.handle(new Request()))
  }
  void get(String pattern, TwoArg handler) {
    println(handler.handle(new Request(),new Response()))
  }
}

def app = new App()
app.get('/', {'NoArg'} as NoArg)
app.get('/', {req->'OneArg'} as OneArg)
app.get('/', {req,res -> 'TwoArg'} as TwoArg) 

将打印

NoArg
OneArg
TwoArg

检查出来:https://groovyconsole.appspot.com/edit/6196672648445952

答案 1 :(得分:0)

我最后写了extension module

/**
 * Example on how to hack Groovy so we can use groovy closure on script routes.
 */
class AppExtension {

  private static Object toHandler(Closure closure) {
    if (closure.maximumNumberOfParameters == 0) {
      NoArg handler = { closure() }
      return handler
    } else if (closure.maximumNumberOfParameters == 1) {
      OneArg handler = { req -> closure(req) }
      return handler
    }
    TwoArg handler = { req, rsp -> closure(req, rsp) }
    return handler
  }

  static void get(App self, String pattern, Closure closure) {
    self.get(pattern, toHandler(closure));
  }

  static void post(App self, String pattern, Closure closure) {
    self.get(pattern, toHandler(closure));
  }
}

我创建了一个接受get的通用Closure方法。然后我检查了闭包参数并将闭包转换为所需的接口。