Tuesday, April 5, 2011

how to find if groovy args contains a particular string

println args

println args.size()

println args.each{arg-> println arg}

println args.class

if (args.contains("Hello"))
    println "Found Hello"

when ran give following error:

[hello, somethingelse]
2
hello
somethingelse
[hello, somethingelse]
class [Ljava.lang.String;
Caught: groovy.lang.MissingMethodException: No signature of method: [Ljava.lang.
String;.contains() is applicable for argument types: (java.lang.String) values:
[Hello]

why can I not do contains?

From stackoverflow
  • Because args is String[] but not List<String>

    You can use

    if (args.grep('Hello'))
        println "Found Hello"
    
  • That's because args is an array of String (just like in Java) and not a String, take a look at the result of:

    print args.getClass()
    
    >>class [Ljava.lang.String;
    

    Notice the [L notation.

    A regular String would result in:

    >>class java.lang.String
    

    The Groovy containers do not have the contains() operation (String does), yet the java.lang.Object of Groovy SDK has the grep() operation (shown on the first reply).

0 comments:

Post a Comment