簡體   English   中英

如何使用對象數組調用 Groovy 閉包

[英]How to call a Groovy Closure with an Object Array

我可能會誤解如何使用可變參數,但根據Groovy Docs for Closures ,對於函數public V call(Object... args) ,arguments 參數“可以是單個值或值列表”。

但是當我嘗試做這樣的事情時:

Closure myClosure = { arg1, arg2, arg3 ->
    println arg1 == null
    println arg2 == null
    println arg3 == null
}
 Object[] argsArray = new Object[]{"John", "Jack", "Mack"}
 myClosure.call(argsArray)

編譯器拋出 groovy.lang.MissingMethodException: No signature of method: .call() is applicable for argument types: ([Ljava.lang.Object;)

在傳遞實際的可變參數時,我什至無法讓可變參數函數工作。

def myVarargsFunction(Object... args){
    println "myVarargsFunction"
    myClosure.call(args)
}

此代碼導致相同的錯誤(當然,在我更改了Closure myClosure的范圍之后)。 我不明白為什么這兩種情況都不起作用。 我知道還有其他方法可以使它起作用,我只是想了解為什么這不起作用。

您可以使用擴展運算符:

    myClosure.call(*args)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM