简体   繁体   English

Groovy-字符串化每个方法

[英]Groovy - String each method

I have just started learning Groovy which looks really awesome! 我刚刚开始学习Groovy,它看起来真的很棒!

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. 我的问题是-按照下面的链接,“每​​个”方法都不是String对象的一部分。 Then how come it works? 那它怎么运作的呢?

http://beta.groovy-lang.org/docs/latest/html/groovy-jdk/ 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. 示例String.each具有1个参数,Map.each具有1个或2个参数,例如entry或key&value。

The relevant code in DefaultGroovyMethods is DefaultGroovyMethods中的相关代码是

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: 字符串toList是:

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

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

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