gpt4 book ai didi

Groovy 可选括号的使用

转载 作者:行者123 更新时间:2023-12-01 16:49:01 25 4
gpt4 key购买 nike

我正在尝试编写一个允许如下语法的 DSL:

foo ["a", "b"], bar: { true }

我认为这应该像定义一个接受属性映射作为第一个参数的方法一样简单,例如:

def foo(Map attr, List blar) { ... }

但似乎这种语法会导致问题,想知道是否有人可以解释原因,以及是否有解决方案允许像顶部的行那样的无括号语法。

groovysh 执行示例:

groovy:000> def foo(Map attr, List blar) { println attr; println blar; }
===> true
groovy:000> foo ["a", "b"], bar: { true }
ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed:
groovysh_parse: 1: expecting EOF, found ',' @ line 1, column 15.
foo ["a", "b"], bar: { true }
^

1 error

at java_lang_Runnable$run.call (Unknown Source)

最佳答案

这不会起作用。它将其理解为对 foo 对象的 getAt 方法调用:

foo["a", "b"]

那么逗号就没有意义了。

您可以使用可变参数:

def foo(Map map, Object... args) { "$map $args" }
a = foo "a", "b", bar: {true}
println a // prints [bar:script_from_command_line$_run_closure1@1f3f7e0] [a, b]

或者颠倒参数顺序:

def foo(Map map, args) { "$map $args" }
a = foo bar: {true}, ["a", "b"]
println a

关于Groovy 可选括号的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375040/

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