Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-10529

Cannot use closures as arguments for varargs method

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Minor
    • Resolution: Duplicate
    • 3.0.10
    • None
    • Compiler
    • Edition Windows 10 Enterprise
      Version 20H2
      Installed on ‎10/‎12/‎2020
      OS build 19042.685
      Experience Windows Feature Experience Pack 120.2212.551.0

    Description

      When I run the following code:

      interface Handler {
          void handle(String)
      }
      
      def foo(Handler... handlers) {
          handlers.each { it.handle('Hello!') }
      }
      
      foo({ print(it) }, { print(it.toUpperCase()) }) 

      I get this error message:

      No signature of method: ConsoleScript8.foo() is applicable for argument types: (ConsoleScript8$_run_closure1, ConsoleScript8$_run_closure2) values:    [ConsoleScript8$_run_closure1@4359df7, ConsoleScript8$_run_closure2@4288c46b]
      

      Apparently, Groovy isn't seeing the closures as instances of Handler. This doesn't happen in Java or Kotlin.

      The workaround is to cast each closure as a Handler instance, but it makes for very awkward usage of the method.

      foo({ print(it) } as Handler, { print(it.toUpperCase()) } as Handler)  

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              ksheppard Kevin Sheppard
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: