gpt4 book ai didi

groovy - Groovy 中带类型参数的闭包

转载 作者:行者123 更新时间:2023-12-04 01:04:40 24 4
gpt4 key购买 nike

我想更明确地说明我关于它们的参数类型的闭包。所以我会写一些类似的东西

List<Y> myCollect(List<X> list, Closure<X,Y> clos) { ... }

我知道 Groovy 不会使用该类型信息,但 Groovy++ 可能会在编译时使用它。这可以实现吗(除了将其放入评论中)?

更新:
标题可能听起来有误导性,但我认为上面的例子会更清楚。我对指定作为某个函数参数的闭包类型感兴趣。假设,我想重新定义内置 collect .所以我有兴趣写 myCollect , 不是书面形式 clos .我想要实现的是获得编译时错误
myCollect(['a', 'ab'], { it / 2 }) // compile error
myCollect(['a', 'ab'], { it.size() }) // OK

最佳答案

您可以定义闭包参数的类型,但上面显示的语法是不正确的。这是一个没有参数类型的闭包:

def concatenate = {arg1, arg2 ->
return arg1 + arg2
}

这是带有参数类型的相同闭包
def concatenate = {String arg1, String arg2 ->
return arg1 + arg2
}

I know that Groovy won't use that type information, but Groovy++ may use it at compile time.



Groovy 确实会进行一些编译时类型检查,但不如 Groovy++(或 Java)多。即使在编译时不使用类型信息,它也会在运行时检查,并且作为一种文档形式也很有值(value)。

关于groovy - Groovy 中带类型参数的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5681601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com