IT story

Groovy :“def x = 0”에서“def”의 목적은 무엇입니까?

hot-time 2020. 5. 24. 10:50
반응형

Groovy :“def x = 0”에서“def”의 목적은 무엇입니까?


다음 코드 조각 ( Groovy Semantics Manual 페이지 에서 발췌)에서 키워드 앞에 할당을 접두어로 붙여야하는 이유는 def무엇입니까?

def x = 0
def y = 5

while ( y-- > 0 ) {
    println "" + x + " " + y
    x++
}

assert x == 5

def키워드는 제거 할 수 있으며,이 조각은 동일한 결과를 생성 할 것입니다. 키워드 효과무엇 def입니까?


기본 스크립트의 구문 설탕입니다. "def"키워드를 생략하면 변수가 현재 스크립트의 바인딩에 들어가고 groovy는 전역 범위 변수처럼 (대부분) 변수를 처리합니다.

x = 1
assert x == 1
assert this.binding.getVariable("x") == 1

대신 def 키워드를 사용하면 변수가 스크립트 바인딩에 포함되지 않습니다.

def y = 2

assert y == 2

try {
    this.binding.getVariable("y") 
} catch (groovy.lang.MissingPropertyException e) {
    println "error caught"
} 

인쇄 : "오류가 발생했습니다"

큰 프로그램에서 def 키워드를 사용하면 변수를 찾을 수있는 범위를 정의하고 캡슐화를 유지하는 데 도움이되므로 중요합니다.

스크립트에서 메소드를 정의하면, 범위 내에 있지 않으므로 기본 스크립트 본문에 "def"로 작성된 변수에 액세스 할 수 없습니다.

 x = 1
 def y = 2


public bar() {
    assert x == 1

    try {
        assert y == 2
    } catch (groovy.lang.MissingPropertyException e) {
        println "error caught"
    }
}

bar()

"오류가 발견되었습니다"

"y"변수는 함수 내에서 범위 내에 있지 않습니다. groovy가 변수에 대한 현재 스크립트의 바인딩을 검사하므로 "x"는 범위 내에 있습니다. 앞에서 말했듯이, 이것은 빠르고 더러운 스크립트를 더 빨리 입력 할 수 있도록하는 구문 설탕입니다 (종종 하나의 라이너).

더 큰 스크립트에서 좋은 습관은 항상 "def"키워드를 사용하여 이상한 범위 지정 문제가 발생하거나 의도하지 않은 변수를 방해하지 않는 것입니다.


Ted의 답변 은 대본에 탁월합니다. Ben의 대답 은 수업의 표준입니다.

Ben이 말했듯이 "Object"로 생각하십시오. 그러나 Object 메소드에 제한을 두지 않기 때문에 훨씬 더 시원합니다. 이것은 수입과 관련하여 깔끔한 영향을 미칩니다.

예를 들어이 스 니펫에서 FileChannel을 가져와야합니다.

// Groovy imports java.io.* and java.util.* automatically
// but not java.nio.*

import java.nio.channels.*

class Foo {
    public void bar() {
        FileChannel channel = new FileInputStream('Test.groovy').getChannel()
        println channel.toString()
    }
}

new Foo().bar()

예를 들어 여기에 모든 것이 클래스 패스에있는 한 '날개'할 수 있습니다.

// Groovy imports java.io.* and java.util.* automatically
// but not java.nio.*
class Foo {
    public void bar() {
        def channel = new FileInputStream('Test.groovy').getChannel()
        println channel.toString()
    }
}

new Foo().bar()

이에 따라 페이지 , def유형 이름에 대한 대체 단순히 별명으로 간주 할 수 있습니다 Object(즉 명시를 당신이 유형에 대해 신경 쓰지 않는다).


이 단일 스크립트에 관한 한 실질적인 차이는 없습니다.

However, variables defined using the keyword "def" are treated as local variables, that is, local to this one script. Variables without the "def" in front of them are stored in a so called binding upon first use. You can think of the binding as a general storage area for variables and closures that need to be available "between" scripts.

So, if you have two scripts and execute them with the same GroovyShell, the second script will be able to get all variables that were set in the first script without a "def".


The reason for "def" is to tell groovy that you intend to create a variable here. It's important because you don't ever want to create a variable by accident.

It's somewhat acceptable in scripts (Groovy scripts and groovysh allow you to do so), but in production code it's one of the biggest evils you can come across which is why you must define a variable with def in all actual groovy code (anything inside a class).

Here's an example of why it's bad. This will run (Without failing the assert) if you copy the following code and paste it into groovysh:

bill = 7
bi1l = bill + 3
assert bill == 7

This kind of problem can take a lot of time to find and fix--Even if it only bit you once in your life it would still cost more time than explicitly declaring the variables thousands of times throughout your career. It also becomes clear to the eye just where it's being declared, you don't have to guess.

In unimportant scripts/console input (like the groovy console) it's somewhat acceptable because the script's scope is limited. I think the only reason groovy allows you to do this in scripts is to support DSLs the way Ruby does (A bad trade-off if you ask me, but some people love the DSLs)


Actually, I don't think it would behave the same...

variables in Groovy still require declaration, just not TYPED declaration, as the right-hand side generally contains enough information for Groovy to type the variable.

When I try to use a variable that I haven't declared with def or a type, I get an error "No such property", since it assumes that I'm using a member of the class containing the code.

참고URL : https://stackoverflow.com/questions/184002/groovy-whats-the-purpose-of-def-in-def-x-0

반응형