在 Groovy 中,如果属性和变量名相同,可以使用 this 关键字来引用属性,这样就能正确地赋值。

以下是一个示例:

class Person {
    String name

    void setName(String name) {
        this.name = name
    }

    void printName() {
        println name
    }
}

def person = new Person()
person.with {
    name = 'John'
    printName()
}

输出结果为:

John

with 代码块中,直接使用 name = 'John' 会被解析为局部变量。为了引用属性而不是变量,可以使用 this.name 或者简写为 name

Groovy 中 with 语句:属性和变量同名时的赋值技巧

原文地址: https://www.cveoy.top/t/topic/b4oW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录