반응형

https://kotlinworld.com/320

<- 반드시 읽어야할 것

 

■ Groovy는 변수의 Data Type을 정의하기 위해 별도의 타입을 구체적으로 정의할 필요없다. (def로 해도 컴파일러가 타입을 추론하기 떄문.) 물론 구체적으로 지정해도 상관없다.

■ Groovy에서 사용하는 클래스는 모두 Java Class에 대응된다.

■ Kotlin과 똑같이 "${변수}"를 사용해 String을 치환할 수 있다.

Groovy Map 사용법

 

참고자료

https://www.guru99.com/groovy-tutorial.html

 


예제코드 1. 반복문, 조건문, 함수

아래의 소스는 Groovy Script로 만들어야합니다.

// 예제 1. groovy 반복문, 조건문, 함수 예제
static void main(String[] args) {
  println "Hello world!"
  def str = "테스트 문자열입니다."
  def num = 1004

  println str
  println num + str
  println num

  // 전통적인 반복문 형태도 사용가능하다.
  for (int i = 1; i <= 5; i ++) {
    println i + "번 반복문: hello world"
  }

  for (j in 1..9) {
    for (i in 1..9) {
      println("$j x $i = ${j*i}")
    }
  }
  check1004(num)
  check1004(1003)
}

def check1004(def num) {
  if (num == 1004) {
    // 문자열 안에 숫자를 넣어 출력하기
    println "$num 은 천사입니다"
  }
  else {
    // + 연산자를 활용하여 문자열 안에 숫자를 넣어 출력하기
    println num + "은 악마입니다"
  }
}

 

예제코드 2. Groovy Class로 int형 변수 출력하기

Groovy Class로 Demo라는 클래스를 만듭니다. 이후 아래의 소스코드 입력.

public class Demo {
    public static void main(String[] args) {
        int x = 104;
        System.out.println(x);
    }
}

출력화면

104

 

예제코드 3. upto 메서드 활용

Consider the following code

2.upto(4) {println "$it"}

It gives an output

2
3
4

 

이론


Groovy는 Java를 발전시킨 객체지향 프로그래밍 언어이다.
Groovy는 Java 문법이 거의 동일하므로 Java 프로그래머라면 금방 적응해서 쓸 수 잇다.
Groovy는 JVM(Java Virtual Machine) 위에서 그대로 돌아가기 때문에 JavaAPI도 문제없이 사용 가능하다.
통합개발환경(IDE) 역시 Java 를 지원하는 툴이라면 Groovy도 지원하는 경우가 대부분이다. (대표적으로 이클립스, 넷빈즈, Intellij IDEA 등이 있다.)
Groovy는 아파치 소트프웨어 재단이 관리하고 있다.

여담. 최근 Maven을 대체하기 시작한 Gradle 빌드 시스템이 이 Groovy를 기반으로 한다. 

(참고자료: 링크)

 

 

In contrast, Groovy supports Dynamic Typing.

Variables are defined using the keyword “def,” and the type of a variable does not need to be declared in advance. The compiler figures out the variable type at runtime and you can even the variable type.

 

 

Consider the following groovy example,

def x = 104
println x.getClass()
x = "Guru99"
println x.getClass()

Output

class java.lang.Integer
class java.lang.String

In Groovy, you can create multiline strings. Just ensure that you enclosed the String in triple quotes.

def x = """Groovy
at
Guru99"""
println x

Output

Groovy
at
Guru99

Note: You can still variable types like byte, short, int, long, etc with Groovy.

But you cannot dynamically change the variable type as you have explicitly declared it.

 

 

 

반응형