KitKarson
KitKarson

Reputation: 5637

Groovy - String each method

I have just started learning Groovy which looks really awesome!

This is very simple example.

"Groovy".each {a -> println a};

It nicely prints as given below.

G
r
o
o
v
y

My question is - 'each' method is not part of String object as per the link below. Then how come it works?

http://beta.groovy-lang.org/docs/latest/html/groovy-jdk/

How can i get the parameters list for a closure of an object?

example String.each has 1 parameter, Map.each has 1 or 2 parameters like entry or key & value.

Upvotes: 5

Views: 10764

Answers (1)

Dylan Bijnagte
Dylan Bijnagte

Reputation: 1356

The relevant code in DefaultGroovyMethods is

public static Iterator iterator(Object o) {
   return DefaultTypeTransformation.asCollection(o).iterator();
}

which contains:

else if (value instanceof String) {
   return StringGroovyMethods.toList((String) value);
}

String toList is:

public static List<String> toList(String self) {
   int size = self.length();
   List<String> answer = new ArrayList<String>(size);
   for (int i = 0; i < size; i++) {
      answer.add(self.substring(i, i + 1));
   }
   return answer;
}

Upvotes: 9

Related Questions