首页 > 解决方案 > 为什么我的 Groovy println 在正确的语句后总是返回 null?

问题描述

我对 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 代替他们的位置。
第二我只是想测试正常
的属性设置第三我想测试自动默认构造函数初始化道具。

在查看文档后,我也尝试用 tap{} 替换 p2(没有用),但我认为这是因为在更新实例时,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 之后我都会得到一个“null”。有人可以解释我错过了什么吗?

标签: stringgroovynulltostring

解决方案


如您所见,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}"
    }
}

一切都会好起来的:-)


推荐阅读