简体   繁体   中英

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.

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;
}

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