【问题标题】:Why does my Groovy println always return null after correct statement?为什么我的 Groovy println 在正确的语句后总是返回 null?
【发布时间】:2019-06-14 13:13:39
【问题描述】:

我对 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”。有人可以解释我缺少什么吗?

【问题讨论】:

    标签: string groovy null tostring


    【解决方案1】:

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

    一切都会好起来的:-)

    【讨论】:

    • 天哪……谢谢。我会支持你,但我的代表太低了哈哈。 edit.. 刚到 15 岁。来吧,你是个陌生人。
    • 现在 20 个?不用担心!很高兴我能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 2011-12-08
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多