我想用Groovy构建一个微观模拟模型,但是我遇到了一个问题,我追溯到了Groovy在Groovy Bean构造函数中处理空值的问题。Groovy Beans标准构造函数如何处理空值?
总之,constructor method that Groovy offers
new Person(nrLegs:calculationResult1, nrArms:calculationResult2)
抛出IllegalArgumentException
如果计算结果之一为空,这是我怎么想的失踪调查数据将被最好的代表。
这对我来说似乎很奇怪:如果我定义了一个没有值的变量double age;
,它显然设置为null。
double testDouble;
assert testDouble == null; // no Problem
如果我做的Groovy bean一样,它具有0.0的值,例如:
class Person {
double age;
int nrLegs, nrArms;
}
然后
Person testPerson = new Person(nrArms:calculationResult1)
assert testPerson.age == null; // Assertion failed. testPerson.age == 0.0
此外,我不能设置属性使用为null Groovy语法:
Person testPerson = new Person(nrArms:calculationResult1)
testPerson.age = null; // IllegalArgumentException
这似乎与上述完全相同的问题。
为什么Groovy会禁止我分配空值?
感谢您的帮助!
编辑:供参考,这里是the entire Person class和StackTrace。
将变量的类型从“int”更改为“Integer”真的解决了这个问题,谢谢!但是,这提出了问题**为什么**?首先,[Groovy没有原始数据类型](http://www.vogella.de/articles/Groovy/article.html#datatypes)。其次,作为我提供的第一个示例,Groovy中的“原始”数据类型(如'double')_can_可以设置为null。这是一个错误? – mzuba
当然,Groovy没有原始类型 - 但不是你的Person类Java吗?(如果没有看到文件后缀,我就说不出来了 - 是不是'.java'? - 它看起来像Java)。 Groovy必须通过自动“拆箱”(在对象和原始类型之间转换)与编译的java类互操作。这是拆箱造成你原来的IllegalArgumentException。 您可以通过确保您的Person类编译为groovy而不是java来避免所有这些。 – winstaan74
文件扩展名是'.groovy',而不是'.java'。我不确定它是否被编译为Groovy,但我想它是,因为否则方法'新人(age:xyz,nrCond:xyz)'不起作用,会吗? – mzuba