Groovy could not find matching constructor?

DirtyMikeAndTheBoys picture DirtyMikeAndTheBoys · Aug 20, 2014 · Viewed 18.2k times · Source

Please note: although this question mentions Mongo it is surely a pure Groovy question at heart.

My MyApp#bootstrap method:

def bootstrap(AppConfiguration config) {
    String h = config.dbHost
    String p = config.dbPort

    println "Mongo is at: ${h}:${p}."

    dao = new MongoDao(host: h, port: p)
}

My MongoDao class (snippet):

class MongoDao implements BasicDao {
    String dbName
    Mongo mongo
    String host
    String port
    Morphia morphia
    Datastore datastore

    MongoDao(String host, String port) {
        this.dbName = "db_myapp"
        this.mongo = new Mongo(host, port)
        this.morphia = new Morphia()
        this.datastore = morphia.createDatastore(mongo, dbName)

        morphia.mapPackage("myappdb.common")
    }
}

When this bootstrap() method runs I get the following exception:

Mongo is at: mymongo01:27017.
Exception in thread "main" groovy.lang.GroovyRuntimeException: Could not find matching constructor for: com.me.myapp.dao.MongoDao(java.util.LinkedHashMap)
    at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1601)
    at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1404)
    at org.codehaus.groovy.runtime.callsite.MetaClassConstructorSite.callConstructor(MetaClassConstructorSite.java:46)

What is going on here? How is it that the host/port are read in and print to STDOUT just find but then when we construct the DAO, they magically turn into a LinkedHashMap?

Answer

injecteer picture injecteer · Aug 20, 2014

if you want to call a constructor with named args, your class MUST provide also a no-arg constructor.

in your case, I'd go for the following call:

dao = new MongoDao( h, p )

as this constructor is doing some job