Groovy If-else和short-hand表示法的行为不同

时间:2017-08-01 05:31:58

标签: groovy

我正面临一个我无法弄清楚的问题。

我有一个浮点数。如果小数部分为0,我想返回一个整数,否则应返回原始浮点数。 以下if-else正常工作并返回20.

def sampleNumber = 20.0
if(sampleNumber == Math.round(sampleNumber)) return sampleNumber as int
else return sampleNumber as float

然而,这不起作用。这将返回20.0

def sampleNumber = 20.0
return sampleNumber == Math.round(sampleNumber)? sampleNumber as int : 
sampleNumber as float

有人可以建议我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

看起来NSDictionary *noNotificationsAttrs = [NSDictionary dictionaryWithObjectsAndKeys:centredStyle, NSParagraphStyleAttributeName, [NSFont fontWithName:@"Raleway-Bold" size:30], NSFontAttributeName, [NSColor clearColor], NSBackgroundColorAttributeName, nil]; 适用于整个表达式。但它没有多大意义:如果我把两个表达式放在括号中,例如

as float

它仍然无法正常工作。我发现的唯一可行解决方案是使用return (sampleNumber == Math.round(sampleNumber)) ? (sampleNumber as int) : (sampleNumber as float) .toInteger()方法:

.toFloat()

如果您从第一个示例中移除return (sampleNumber == Math.round(sampleNumber)) ? sampleNumber.toInteger() : sampleNumber.toFloat() 并返回,例如像as float那样的字符串然后'float'会返回您的期望。我将调查它以找出这种奇怪行为的确切原因。