Skip to content

Groovy 치트시트

Java와 비슷한 문법과 강력한 기능을 갖춘 JVM 기반의 동적 언어입니다.

01

시작하기

Hello World

Groovy는 Java와 호환되지만 더 간결합니다.

groovy
println "Hello, World!"

변수

def로 동적 타이핑을 하고, 명시적 타입도 사용할 수 있습니다.

groovy
def x = 10
def s = "hello"
int y = 20

클로저

클로저는 코드 블록이며, 'it'이 기본 파라미터입니다.

groovy
def square = { n -> n * n }
println square(5)

[1, 2, 3].each { println it }

문자열

큰따옴표는 ${} 보간을 지원하지만 작은따옴표는 지원하지 않습니다.

groovy
def name = "World"
println "Hello, ${name}!"
println 'No interpolation'
02

자료구조

리스트

<<로 리스트에 추가하며, collect는 map에 해당합니다.

groovy
def lst = [1, 2, 3]
lst << 4
lst.each { println it }
lst.collect { it * 2 }

맵

맵은 [:] 리터럴로 만들고, .property 방식으로 접근합니다.

groovy
def m = [a: 1, b: 2]
m.c = 3
println m.a
m.each { k, v -> println "$k=$v" }

범위(Range)

범위도 일급 객체로 취급됩니다.

groovy
def r = 1..5
r.each { println it }
(1..10).findAll { it % 2 == 0 }
03

심화

클래스

클래스는 Java와 비슷하지만 보일러플레이트가 훨씬 적습니다.

groovy
class Person {
    String name
    int age
}

def p = new Person(name: "Alice", age: 30)
println p.name

GStrings

GString은 ${} 안에 임의의 표현식을 사용할 수 있습니다.

groovy
def items = [1, 2, 3]
println "Items: ${items.join(", ")}"
println "Sum: ${items.sum()}"

Was this helpful?