[英]what does the groovy compiler make of gradle dependsOn syntax
我了解 gradle DSL
task doTask { logger.info "some text" }
將實際調用項目委托對象上的方法 task(String,Closure)。 它或多或少是一個簡寫
task("doTaks", {logger.info("some text")})
這一切都很好。 但是當我試圖理解我在第三方構建腳本中看到的一些 gradle DSL 語法時,事情變得復雜了:
task doTask (dependsOn: 'otherTask'){logger.info "some text"}
我認為 groovy 將從 (dependsOn: 'otherTask') 創建一個地圖,並且不知何故 Project 方法
task(Map args, String name, Closure config)
將被調用。 但是這些額外的括號如何發揮作用,為什么它們是必要的,groovy 是如何弄清楚我們在這里想要什么的? 以我最低限度的 groovy 技能,語法對我來說完全違反直覺。 我永遠不會猜到我必須這樣做才能使它工作。
所以,這就是問題:groovy 如何弄清楚如何處理這個命令:
task doTask (dependsOn: 'otherTask'){ // some code }
您可以使用以下語法之一調用 groovy 方法:
參數必須在括號內用逗號分隔:
method(arg1, arg2, ..., argN, argClosure)
Args 必須全部以逗號分隔,不帶括號:
method arg1, arg2, ..., argN, argClosure
如果最后一個參數是一個閉包,則所有前面的參數必須在括號內全部用逗號分隔,並且argClosure
括號后的代碼塊(在大括號{...}
)將被解釋為最后一個Closure
參數argClosure
:
method(arg1, arg2, ..., argN) { ... }
如果您不希望大括號內的代碼塊被解釋為前面方法調用的Closure
參數; 然后用分號結束方法調用:
// Because of `;` following { ... } is not a Closure argument for `method` method(arg1, arg2, ..., argN); { ... }
可以使用命名參數語法調用接受單個Map
或Map
和閉包作為參數的方法; 這會將每個命名參數轉換為映射中的一個條目,最后一個參數將是一個閉包。 這將創建以下直觀的語法變體:
method(name1: arg1, name2: arg2, ..., nameN: argN, argClosure) method name1: arg1, name2: arg2, ..., nameN: argN, argClosure method(name1: arg1, name2: arg2, ..., nameN: argN) { ... }
Groovy 提供了大量的語法糖,因此可以在此周圍找到其他直觀的變體; 但這讓您感受到了 groovy 處理Closure
參數的方式。
以下是這些不同的方法調用方式的工作演示:
import java.time.LocalDateTime
def handleWithClosure(data1, data2, closure) {
closure("$data1. $data2")
}
def logger = { println "${LocalDateTime.now()} - $it" }
handleWithClosure(1, 'All within parenthesis', logger)
handleWithClosure 2, 'All without parenthesis', logger
handleWithClosure(3, 'List of arguments within parenthesis and closure outside') { logger(it) }
def handleMapWithClosure(map, closure) {
handleWithClosure(map['num'], "[Named Arguments/Map based] ${map['msg']}", closure)
}
handleMapWithClosure(msg: 'All within parenthesis', num: 1, logger)
handleMapWithClosure msg: 'All without parenthesis', num: 2, logger
handleMapWithClosure(msg: 'List of arguments within parenthesis and closure outside', num: 3) { logger(it) }
運行它你可以看到它是如何處理所有這些語法選項的。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.