Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

데이터로써의 코드 (또는 "클로저")

Groovy는 다른 대부분의 컴파일 언어와 달리 코드를 데이터처럼 다룰 수 있습니다. 즉, 코드 덩어리를 마치 정수나 문자열처럼 이리저리 전달할 수 있다는 뜻입니다. 다음 코드를 참고하세요:

"it * it"이라는 표현식을 감싸고 있는 괄호(curly braces)는 Groovy 컴파일러에게 괄호 안에 있는 표현식이 코드라는 사실을 알려줍니다. 소프트웨어 세상에서는 이를 클로저(closure)라고 부릅니다. 이 경우 "it"은 클로저에 주어진 값을 의미합니다. 이제 이 컴파일된 함수는 "square"라는 변수에 저장됩니다. 이제 아래와 같은 코드를 쓸 수 있습니다:

그리고 결과는 81이 됩니다.

여기까지는 별로 흥미롭지 않습니다. 하지만 함수 "square"를 값으로써 여기저기 전달할 수 있다는 사실에 주목하세요. Groovy에는 클로저를 인자로 받는 몇몇 내장 함수가 존재합니다. 한가지 예제는 배열의 "collect" 메서드 입니다. 다음 코드를 시도해보세요:

위 표현식은 값이 1,2,3,4 인 배열을 만들고 "collect" 메서드를 호출하면서 우리가 위에서 정의한 클로저를 전달합니다. collect 메서드는 배열의 각 아이템을 순회하면서 클로저를 호출하면서 해당 아이템은 인자로 넘깁니다. 그리고 그 결과를 새로운 배열에 담습니다. 따라서 위 코드를 수행한 결과는 다음과 같습니다:

클로저를 인자로 받는 더 많은 메서드들을 찾아보려면 Groovy GDK 문서 를 참고하세요.

기본적으로 클로저는 "it" 이라는 이름의 인자를 갖지만 여러 인자에 이름을 지정해서 클로저를 만들 수도 있습니다. 예를 들어 Map.each() 메서드는 두 개의 인자를 갖는 클로저를 인자로 받습니다:

위 코드의 결과는 다음과 같습니다:

More Closure Examples

Here are a few more closure examples. This first one shows a couple of things. First, the closure is interacting with a variable outside itself. That is, the closure's purpose is to put together the parts of a stock order held in the array orderParts, by adding (appending) it to the variable fullString. The variable fullString is not in the closure. The second thing that is different about this example is that the closure is "anonymous", meaning that it is not given a name, and is defined in the place where the each method is called.

You can probably guess what this prints out.

The next example is another anonymous closure, this time, summing up the values stored in a map.

Dealing with Files

Reading data from files is relatively simple. First create a text file, and call it myfile.txt. It doesn't matter what's in it, just type some random text into it and save it on your C: drive in the \temp directory. Then type the following code in the groovyConsole:

This should print out every line in the file prefixed with "File line: ". The first two lines of the code simply declare variables to specify where the file is located. The variable names don't have any special significance, and as you can see, all we do is combine them when we use them. Note that because the backslash character has special meaning in groovy, you have to use two of them to tell it that you '''really''' mean a backslash.

The next line that starts "myFile =" creates a new File object. An object is simply a collection of related methods and data. For example, a file object might have data describing its location, in this case "C:\temp\myfile.txt", and maybe a method to delete the file if it exists. In this case the only method we are going to use is the eachLine method, which we call in the last line of code. The line before that is a simple closure definition, that you have seen several times by this point.

Dealing with strings

Strings in Groovy have all the same functionality of Java strings. That is, a Groovy string is just a Java string with a few extra things added to it. Because of that, we can refer to the Java documentation for the String class to find out some of the interesting things we can do with it. For example, look in the section entitled '''Method Summary''' at the description for the '''split''' method. This method does something very useful, which is to split a string based on a regular expression. We will talk more about regular expressions later, but for now the only thing you have to know is that the simplest regular expression is a single character. So let's say that we want to split up the components of the date "2005-07-04", so that we can add one to the year to get the date of next fourth of July. We might:

This code brings together a bunch of things we have talked about before. There are two new things, first is the use of the split method on a String. Second is the call of toInteger() on a String. This call to toInteger simply tells Groovy that you want to treat that data as a number rather than a String. See what happens if you run the same code without ".toInteger()" at the end of the third line.

Another thing you might notice is that toInteger is not listed in the Java documentation for string. That is because it is one of the extra features that Groovy has added to Strings. You can also take a look at the documentation for the Groovy extensions to Java objects.

  • No labels