2014-09-21 56 views
2

我在搖籃只是新手,雖然我讀我整個​​follwoing代碼示例附帶的搖籃手冊:Gradle 4.times。美元是什麼?

task count << { 
    4.times { print "$it " } 
} 

它打印1 2 3 4。爲什麼?什麼是$it,爲什麼如果我們更換$it爲 「一」,我們將獲得

a a a a 

而且

task count << { 
    print "$it " 
    print "$it " 
    print "$it " 
    print "$it " 
} 

使輸出task ':count' task ':count' task ':count' task ':count'

回答

2

做甚至不勉強知道的gradle什麼是,但似乎$it迭代器的簡稱。當您說4.times (token)時,您正在執行(token)四次,每次都會將$it綁定到當前迭代。

同樣,我幾乎不知道Gradle是什麼,但在第二個示例中,$it似乎在迭代給定的構建任務。當前的任務是count,因此它會打印該任務的字符串表示形式。沒有隱式循環,那個詞法範圍中就沒有更具體的迭代器。

+0

嗯......但是如果我只寫print $ 4次,我會收到'task':count'task':count'task':count'task':count''。 – 2014-09-21 14:02:18

+0

您可以將其擴展爲一個完整的示例並將其編輯爲原始問題嗎?我的猜測是,這只是我所說的泛化 - 迭代給定的構建任務 – 2014-09-21 14:03:09

+0

當然,我已經更新了Q. – 2014-09-21 14:04:48

2

所謂隱式參數$it在上述評論的鏈接,文檔的Groovy後討論的,具體這裏:Implicit parameter。它是閉包,除非有明確的空參數列表。

實施例與$it

def greeting = { "Hello, $it!" } 
assert greeting('Patrick') == 'Hello, Patrick!' 

而不$it

def magicNumber = { -> 42 } 

// this call will fail because the closure doesn't accept any argument 
magicNumber(11) 
+0

(示例來自鏈接) – ronaldw 2016-02-24 21:30:59

相關問題