【发布时间】: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