我试过了:
groovy:000> Set<String> s = ["a", "b", "c", "c"]
===> [a, b, c]
groovy:000> s
Unknown property: s
Run Code Online (Sandbox Code Playgroud)
我希望能够将它作为一个集合使用,但即使我明确地传递它,它也会将它变成一个ArrayList:
groovy:000> joinList(["a", "b", "c", "c"])
ERROR groovy.lang.MissingMethodException:
No signature of method: groovysh_evaluate.joinList() is applicable for argument types: (java.util.ArrayList) values: [[a, b, c, c]]
Possible solutions: joinList(java.util.Set)
Run Code Online (Sandbox Code Playgroud)
Dón*_*nal 24
出现此问题的原因是您使用Groovy Shell来测试代码.我不太多使用Groovy shell,但它似乎忽略了类型
Set<String> s = ["a", "b", "c", "c"]
Run Code Online (Sandbox Code Playgroud)
相当于
def s = ["a", "b", "c", "c"]
Run Code Online (Sandbox Code Playgroud)
而后者当然会创造一个List.如果你在Groovy控制台中运行相同的代码,你会发现它确实创建了一个Set
Set<String> s = ["a", "b", "c", "c"]
assert s instanceof Set
Run Code Online (Sandbox Code Playgroud)
Set在Groovy中创建其他方法包括
["a", "b", "c", "c"].toSet()
Run Code Online (Sandbox Code Playgroud)
要么
["a", "b", "c", "c"] as Set
Run Code Online (Sandbox Code Playgroud)
dma*_*tro 15
Groovy> = 2.4.0
设置interpreterMode为truegroovy shell by
:set interpreterMode true
Run Code Online (Sandbox Code Playgroud)
应该解决这个问题
Groovy <2.4.0
向变量添加类型使其成为shell环境无法使用的局部变量.
使用如下 groovysh
groovy:000> s = ['a', 'b', 'c', 'c'] as Set<String>
===> [a, b, c]
groovy:000> s
===> [a, b, c]
groovy:000> s.class
===> class java.util.LinkedHashSet
groovy:000>
Run Code Online (Sandbox Code Playgroud)