为什么我的Groovy println在正确的语句后总是返回null?

时间:2019-06-14 13:13:39

标签: string groovy null tostring

我对groovy非常陌生,我想知道为什么我的代码之后却收到null。我有一个非常基本的App.groovy和Person.groovy,我认为我的错误在于关闭自动返回功能,但我不确定

package firstGradleGroovyBuild

class App {
    static void main(def args) {
        def myList = [1,2,"James","4"]

        myList.each {
            println("$it is of ${it.class}")
        }
        println()

        Person person = new Person()
        person.age = 13
        person.address = "Home"
        println(person)

        Person p2 = new Person()
        p2.firstName = "Joe"
        p2.lastName = "Shmo"
        p2.age = 23
        p2.address = "Away"
        println p2

        Person p3 = new Person(firstName: "Smoky", lastName: "Robinson", age: 24, address: "Mountains")
        println p3
    }
}

这是我的应用程序,我只是在尝试测试一些不同的东西。
首先,我想确保在不设置名字和姓氏的情况下,我会在他们的位置收到null。
其次,我只想测试正常的属性设置
第三,我想测试自动默认构造函数的初始化道具。

在查看文档后,我也尝试过替换p2 w / tap {无效(但不起作用),但是我认为这是因为tap仅用作首选项,以节省更新实例时一遍又一遍地键入前缀p2的麻烦。 。

Person p2 = new Person().tap {
            firstName = "Jo"
            lastName = "Mo"
            age = 23
            address = "Away"
        }
        println p2

这是我的Person班

package firstGradleGroovyBuild

class Person {
    String firstName
    String lastName
    int age
    def address

    String toString(){
        println("${firstName} ${lastName} of age ${age} lives at ${address}")
    }

}

我的输出几乎是预期的 :println中的所有内容都是正确的。

1 is of class java.lang.Integer
2 is of class java.lang.Integer
James is of class java.lang.String
4 is of class java.lang.String

null null of age 13 lives at Home
null
Joe Shmo of age 23 lives at Away
null
Smoky Robinson of age 24 lives at Mountains
null

Process finished with exit code 0

但是每次println之后我都会得到一个“空”。有人可以解释我所缺少的吗?

1 个答案:

答案 0 :(得分:2)

如您所见,println返回null

因此,在您的toString中,您要打印出字符串,然后返回null

toString不应进行任何打印。

将您的班级更改为:

class Person {
    String firstName
    String lastName
    int age
    def address

    String toString(){
        "${firstName} ${lastName} of age ${age} lives at ${address}"
    }
}

一切都会好起来的:-)