简体   繁体   中英

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. Splitting a String returns a String Array, which I thought would be regarded as a Collection in Groovy. Other Collection methods do work on a String Array, so my question is: have I encountered a bug?

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]

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.

As stated in the groovydoc, split will return an array of string, which doesn't have a lot of groovy enhancements. tokenize returns a list instead of an array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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