Adam Lewis
Adam Lewis

Reputation: 943

Can't pass closures in groovy

I am trying to run a basic example for the Geb library (http://www.gebish.org/manual/current/intro.html#introduction). Here is the code:

import geb.Browser

Browser.drive {
   go "http://google.com/ncr"

    // make sure we actually got to the page
    assert title == "Google"

    // enter wikipedia into the search field
    $("input", name: "q").value("wikipedia")

    // wait for the change to results page to happen
    // (google updates the page dynamically without a new request)
    waitFor { title.endsWith("Google Search") }

    // is the first link to wikipedia?
    def firstLink = $("li.g", 0).find("a.l")
    assert firstLink.text() == "Wikipedia"

    // click the link 
    firstLink.click()

    // wait for Google's javascript to redirect to Wikipedia
    waitFor { title == "Wikipedia" }
}

When I try to run this (using Eclipse's groovy support) I get the following exception:

Caught: groovy.lang.MissingMethodException: No signature of method: static geb.Browser.drive() is applicable for argument types: (ExampleScript$_run_closure1) values: [ExampleScript$_run_closure1@2a62610b]
Possible solutions: drive(groovy.lang.Closure), drive(geb.Browser, groovy.lang.Closure), drive(geb.Configuration, groovy.lang.Closure), drive(java.util.Map, groovy.lang.Closure), print(java.lang.Object), print(java.io.PrintWriter)
groovy.lang.MissingMethodException: No signature of method: static geb.Browser.drive() is applicable for argument types: (ExampleScript$_run_closure1) values: [ExampleScript$_run_closure1@2a62610b]
Possible solutions: drive(groovy.lang.Closure), drive(geb.Browser, groovy.lang.Closure), drive(geb.Configuration, groovy.lang.Closure), drive(java.util.Map, groovy.lang.Closure), print(java.lang.Object), print(java.io.PrintWriter)
at ExampleScript.run(ExampleScript.groovy:21)

I think this is saying that the closure I am passing to the static Browser.drive method is not type compatible with groovy.lang.Closure, but I don't know why. Simple groovy hello world scripts work fine but passing a closure to a method always returns a similar error.

Upvotes: 4

Views: 2995

Answers (1)

djangofan
djangofan

Reputation: 29669

Plagiarized from: http://groovy.codehaus.org/Differences+from+Java

Java programmers are used to semicolons terminating statements and not having closures. Also there are instance initializers in class definitions. So you might see something like:

class Trial {
  private final Thing thing = new Thing ( ) ;
  { thing.doSomething ( ) ; }
}

Many Groovy programmers eschew the use of semicolons as distracting and redundant (though others use them all the time - it's a matter of coding style). A situation that leads to difficulties is writing the above in Groovy as:

class Trial {
  private final thing = new Thing ( )
  { thing.doSomething ( ) }
}

This will throw a MissingMethodException!

Upvotes: 2

Related Questions