[groovy] Groovy의 숨겨진 기능?

이 스레드에서 Groovy가 잊혀진 것 같아서 Groovy에 대해 동일한 질문을 할 것입니다.

  • Groovy 코어에 대한 답변을 제한하십시오.
  • 답변 당 하나의 기능
  • 문서에 대한 링크뿐만 아니라 기능의 예와 간단한 설명을 제공합니다.
  • 첫 번째 줄로 굵은 제목을 사용하여 지형지 물에 레이블 지정

또한보십시오:

  1. Python의 숨겨진 기능
  2. Ruby의 숨겨진 기능
  3. Perl의 숨겨진 기능
  4. 자바의 숨겨진 기능



답변

확산 점 연산자 사용

def animals = ['ant', 'buffalo', 'canary', 'dog']
assert animals.size() == 4
assert animals*.size() == [3, 7, 6, 3]

이것은의 바로 가기입니다 animals.collect { it.size() }.


답변

방법은이를 끌 수 있습니다 :

 myObj1.setValue(10)
 otherObj.setTitle(myObj1.getName())
 myObj1.setMode(Obj1.MODE_NORMAL)

이것으로

 myObj1.with {
    value = 10
    otherObj.title = name
    mode = MODE_NORMAL
 }


답변

해시를 의사 객체로 사용.

def x = [foo:1, bar:{-> println "Hello, world!"}]
x.foo
x.bar()

덕 타이핑과 결합하면이 접근 방식으로 먼 길을 갈 수 있습니다. “as”연산자를 쓸 필요도 없습니다.


답변

엘비스 에 대해 아는 사람 있나요?

def d = "hello";
def obj = null;

def obj2 = obj ?: d;   // sets obj2 to default
obj = "world"

def obj3 = obj ?: d;  // sets obj3 to obj (since it's non-null)


답변

객체에 어떤 메소드가 있는지 알아내는 것은 metaClass에 요청하는 것만 큼 쉽습니다.

"foo".metaClass.methods.name.sort().unique()

인쇄물:

["charAt", "codePointAt", "codePointBefore", "codePointCount", "compareTo",
 "compareToIgnoreCase", "concat", "contains", "contentEquals", "copyValueOf",
 "endsWith", "equals", "equalsIgnoreCase", "format", "getBytes", "getChars",
 "getClass", "hashCode", "indexOf", "intern", "lastIndexOf", "length", "matches",
 "notify", "notifyAll", "offsetByCodePoints", "regionMatches", "replace",
 "replaceAll", "replaceFirst", "split", "startsWith", "subSequence", "substring",
 "toCharArray", "toLowerCase", "toString", "toUpperCase", "trim", "valueOf", "wait"]


답변

누락 된 정적 메서드를 가로 채려면 다음을 사용하십시오.

 Foo {
    static A() { println "I'm A"}

     static $static_methodMissing(String name, args) {
        println "Missing static $name"
     }
 }

Foo.A()  //prints "I'm A"
Foo.B()  //prints "Missing static B"


답변

구조화

Groovy에서는 다른 이름으로 불릴 수 있습니다. 클로저에서 구조화라고합니다. 얼마나 편리 할 수 ​​있는지 결코 믿지 못할 것입니다.

def list = [1, 'bla', false]
def (num, str, bool) = list
assert num == 1
assert str == 'bla'
assert !bool