[Groovy] 기본 문법

2023. 4. 10. 17:21Programming Languages/Groovy

Groovy란?

Java에 python이나 ruby 등의 특징을 더한 동적 객체 프로그래밍 언어이다. Gradle에서 build.gradle에서 사용되는 언어가 기본적으로 Groovy이기 때문에 기본 문법을 알면 좋다.

변수

동적 타입 바인딩

def a = 20  // 값을 할당할 때 a 변수의 타입이 결정됨
a = "문자열" // 다른 값 할당 시 변수 타입이 변함
b = "문자열" // 변수 선언 시 def 생략 가능

정적 타입 바인딩

int a = 20   // 변수 a는 int로 자료형이 고정됨
a = "문자열"  // 다른 타입을 할당하면 오류 발생

문자열과 자동 형변환

String a = "문자열" // 변수 a는 String으로 자료형 고정
a = 20 // 정수 20이 문자열 "20"으로 자동 형변환 후 a에 할당됨

자바 변수 선언

java.util.Date a = new java.util.Date() // 자바 문법 사용 가능
Date b = new Date(); // java.util 패키지는 기본 import

리스트와 맵

리스트

scoreList = [90, 80, 100, 87] // ArrayList 객체 생성
println scoreList[2] // 배열처럼 사용 가능
println scoreList.get(2) // arrayList.get() 호출
println scoreList.size() // 4
nameList = ["홍길동", "임꺽정", "장보고"]
println nameList[1]
emptyList = [] // 빈 리스트

scoreMap = ["국어":100, "영어":90, "수학":100, "사회":89]
println scoreMap["수학"]   // 변수[키] 형태로 값 접근
println scoreMap.수학      // 변수.키 형태로 값 접근
println scoreMap.getClass  // java.util.LinkedHashMap 출력
scoreMap.수학 = 93    // 맵의 값 변경
println scoreMap.수학 // 93
emptyMap = [:]       // 빈 맵 생성

분기

if-else 문

if (true or false) {
	// ...
} else if (...) {
	// ...
} else {
	// ...
}

조건 연산자

age = 17
title = (age < 19) ? "청소년" : "성인"

switch 문

x = "aaa"
result = ""
switch (x) {
	case "aaa":
		result = "aaa"
	case "123":
		result += "123"
	case [1, 20, 3.14, true]:
		result = "숫자, 문자열, 불린 값"
		break
	case 100..200:
		result = "100 ~ 200 값"; break
	case Number:
		result = "기타 숫자 값"
		break
	default:
		result = "기타"
}
println result
  • Groovy의 switch 문은 자바와 달리 실수, 불린, 객체도 다룰 수 있다.

반복문

while 문

while (조건) { ... }

for 문

for (int i = 0; i < 5; i++) {}
for (i in 0..9) {}
for (i in [100, 90, 95, 80]) {}
for (i in 배열) {}
for (entry in 맵) {}
for (c in 문자열) {}

목록.each({ ... })
맵.each({key, value -> ...})
목록.eachWithIndex({obj, i -> ...})
맵.eachWithIndex({obj, i -> ...})

메서드와 클로저

메서드 정의 및 호출

def plus(a, b) {
	a + b
}

int minus(int a, int b) {
	return a - b
}

// 괄호 생략 가능
test.systemProperty 'some.prop', 'value'
test.systemProperty('some.prop', 'value')

클로저 정의

plus = { a, b -> a + b }
println plus(10, 20)
plus = { int a, int b -> return a + b }

// 기본 클로저 정의
repositories() { println "in a closure" }
// 괄호 안으로 옮김
repositories({ println "in a closure" })
// 괄호 제거
repositories {
    println "in a closure"
}

클로저 Free 변수

pi = 3.14159
getCircleArea = { radius ->
	// pi는 Free 변수
	pi * radius * radius
}

클로저 it 파라미터

plus = {
	it[0] + it[1]
}
println plus([10, 20])

클로저 반환 값

plus = { a, b ->
	a + b
}
// return이 없으면 마지막 문장의 실행 값 반환
// 마지막 문장의 실행 값이 없으면 null 반환

클래스

클래스 정의 및 사용

class Test {
	void hello() {
		println "Hello World!"
	}
}

t = new Test()
t.hello()

프로퍼티 선언과 사용

Class Student {
	Integer no
	String name
	Date registerDate
}
p = new Person(no:1, name:"지용", registerDate:new Date())
println s.no + "," + s.name + "," + s.registerDate

문자열과 GString

문자열 표현(”, ‘, /)

println "I like 'groovy'."
println 'I like "groovy".'
println (/I like "groovy"./)

멀티 라인

intro = """ Hi, My name is J.
I am teaching Groovy script.
Let's go Groovy Programming."""

GString

name = "jiyong"
println "Hi, $name."   // Hi, jiyong.
println "Hi, \$name."  // Hi, $name.

Gstring과 String

str1 = "jiyong"
str2 = "My name is $str1"
str3 = str1 + str2

assert str1 instanceof String
assert str2 instanceof GString
assert str3 instanceof String

GString과 클로저

now = new Date()
str1 = "일반객체: $now 입니다."
str2 = "파라미터 없는 클로저: ${new Date()}"
str3 = "파라미터 있는 클로저: ${writer -> writer << new Date()}"