How to call buildConfigField() from another function in Gradle?

Viewed 413

Here's an extremely simplified version of what I'm trying to do in Gradle for my Android app:


android {

    buildTypes {

        debug {

            buildConfigFieldMyWay("keyName", "keyValue")
            buildConfigField("String", "keyName", "keyValue")  }
        }
    }

}

def buildConfigFieldMyWay(String keyName, String keyValue) {
    buildConfigField("String", keyName, keyValue)
}

The real version is more complex, which is why it would be nice to organize what I'm doing into separate functions.

The problem is that when I do a Gradle sync, I get this error: No signature of method: build_byqgds5lao5ipgp4gk5ftyud4.android() is applicable for argument types: (build_byqgds5lao5ipgp4gk5ftyud4$_run_closure2) values: [build_byqgds5lao5ipgp4gk5ftyud4$_run_closure2@536e468e]

I think this has to do with the DSL Gradle uses with Android; that when buildConfigField() is called inside of android { buildTypes { debug, that it is running buildConfigField() on a BuildType object. If I call it from a separate function, there is no BuildType for it to operate on.

So I either need to modify the DSL so that my function (buildConfigFieldMyWay()) can be called in android { buildTypes { debug and operate on the BuildType object, or I need to pass the BuildType to the function. There's likely some simple syntax I need to use here that I'm not finding. What is it?

1 Answers

You can pass the build type inside the function buildConfigFieldMyWay:

def buildConfigFieldMyWay(buildType, String keyName, String keyValue) {
    buildType.buildConfigField("String", keyName, keyValue)
}

And then, you can get the build type using it:

android {
    buildTypes {
        debug {
            buildConfigFieldMyWay(it, "keyName", "keyValue")
            buildConfigField("String", "keyName", "keyValue")
        }
    }
}
Related