How to add dependency using a method in Gradle

Viewed 308

I can add a module dependency using either of

  • aar dependency
  • local project module Right now I am able to accomplish same using below

    if (foo(":awesomemodule")) {
        implementation 'com.example.app:awesomemodule:1.0'
    
    }
    else {
        implementation project(':awesomemodule')
    }
    

Now I want to repeat this code for multiple dependencies and want to create a method for same.

I want something like this

customAddImplementation(':awesomemodule')

ext.customAddImplementation = { moduleName ->
    if (foo(moduleName)) {
        return implmentation('com.example.app' + moduleName + ':1.0')
    } else {
        return project(path: moduleName)
    }
}

But this approach is not working, as implementation() definition is not found when i add my dependencies using customAddImplementation(':awesomemodule')

1 Answers

Something like this should work:

def customModulePath(String moduleName) {
    if (foo(moduleName)) {
        return "com.example.app:$moduleName:1.0")
    } else {
        return project(":$moduleName")
    }
}

dependencies {
    implementation(customModulePath('awesomemodule'))
}

And bonus point: since the function doesn't try to add the custom module path to the implementation dependencies, but simply returns its path, you can ruse it to add dependencies to any other configuration.

Related