简体   繁体   English

Groovy中的findResults方法似乎不适用于字符串数组

[英]The findResults method in Groovy seems not to work on a String Array

I tried to invoke method "findResults" on a split String, but got a compilation error. 我尝试在拆分的String上调用方法“ findResults”,但出现编译错误。 Splitting a String returns a String Array, which I thought would be regarded as a Collection in Groovy. 拆分一个字符串会返回一个字符串数组,我认为这将被视为Groovy中的Collection。 Other Collection methods do work on a String Array, so my question is: have I encountered a bug? 其他Collection方法也可以在字符串数组上工作,所以我的问题是:我遇到错误了吗?

def names = "john paul pete"
assert names.split().findResults{if (it.startsWith("p")) return it.capitalize()}.join(" ") == "Paul Pete"

Result: groovy.lang.MissingMethodException: No signature of method: [Ljava.lang.String;.findResults() is applicable for argument types: (gard_split_check$_run_closure2) values: [gard_split_check$_run_closure2@722b302] 结果:groovy.lang.MissingMethodException:方法的无签名:[Ljava.lang.String; .findResults()适用于参数类型:(gard_split_check $ _run_closure2)值:[gard_split_check $ _run_closure2 @ 722b302]

NB I know I can get the proper result by replacing split() with tokenize() in the above code, or by casting the result of the split() method to a List. 注意我知道可以通过在上面的代码中用tokenize()替换split()或将split()方法的结果强制转换为List来获得正确的结果。

As stated in the groovydoc, split will return an array of string, which doesn't have a lot of groovy enhancements. 如groovydoc中所述, split将返回一个字符串数组,该字符串没有很多groovy增强。 tokenize returns a list instead of an array: tokenize返回列表而不是数组:

def names = "john paul pete"
assert names.tokenize().findResults { 
    if (it.startsWith("p")) it.capitalize()
}.join(" ") == "Paul Pete"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM