1

I've been looking for a few minutes over the internet on how to create functions and call them inside build.gradle without success. Since I found nothing I'm not sure if I'm searching for the right concept-keywords or if that's even possible.

I have two buildTypes:

release {

}

debug {

}

And I woud like to call this snippet() below inside both of them without duplicating it, or in other words, to create a function:

def propsFile = rootProject.file('properties')
            def M_PROP = "mProp"

            if (propsFile.exists()) {
                //Math
            }

Generating something like:

buildTypes {
        release {
              snippet()
            }
        }

        debug {
              snippet()
        }
    }

is that possible and how am I able to do this?

Victor Oliveira
  • 3,293
  • 7
  • 47
  • 77
  • 1
    Does this help: https://stackoverflow.com/questions/27777591/how-to-define-and-call-custom-methods-in-build-gradle – Rax Jan 18 '18 at 14:58

1 Answers1

1

Perhaps you want

buildTypes {
   [release, debug].each { buildType ->
      if (foo) {
          buildType.doStuff()
      }
   }
}

Or maybe

ext.snippet = { buildType -> 
    if (foo) {
       buildType.doStuff()
    }
}
buildTypes {
    snippet(release)
    snippet(debug)
}

Note: There's also the with { ... } method in groovy so

buildType.doStuff1()
buildType.doStuff2()
buildType.doStuff3()

can be written as

buildType.with {
    doStuff1()
    doStuff2()
    doStuff3()
}
lance-java
  • 25,497
  • 4
  • 59
  • 101