避免代码重复 - 如何在 gradle 中创建函数(并调用它们)?

Avoid code duplication - How to create functions (and call them) in gradle?

我在互联网上搜索了几分钟如何创建函数并在 build.gradle 中调用它们,但没有成功。因为我什么也没找到,所以我不确定我是否正在搜索正确的概念关键字,或者这是否可能。

我有两个buildTypes:

release {

}

debug {

}

我想在下面的两个函数中调用这个 snippet() 而不重复它,或者换句话说,创建一个函数:

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

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

生成如下内容:

buildTypes {
        release {
              snippet()
            }
        }

        debug {
              snippet()
        }
    }

这可能吗?我怎样才能做到这一点?

也许你想要

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

或者也许

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

注意:groovy中还有with { ... }方法,所以

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

可以写成

buildType.with {
    doStuff1()
    doStuff2()
    doStuff3()
}