【发布时间】:2014-11-11 20:42:42
【问题描述】:
下面的代码可以用@CompileStatic编译吗?
import groovy.transform.CompileStatic
@CompileStatic
class CompileStaticTest {
List<Number> numbers = []
void addWithCase(something) {
switch (something) {
case Integer: numbers << something; break // compile error
case Float: numbers << something; break // compile error
}
}
void addWithInstanceof(something) {
if (something instanceof Integer) {
numbers << something // compile error
}
if (something instanceof Float) {
numbers << something // compile error
}
}
}
用法:
test = new CompileStaticTest()
test.addWithCase(11)
test.addWithCase(12f)
test.addWithCase('13')
test.addWithInstanceof(21)
test.addWithInstanceof(22f)
test.addWithInstanceof('23')
println test.numbers
目前存在编译错误:
[Static type checking] - Cannot call <T> java.util.List <Number>#leftShift(T) with arguments [java.lang.Object]
something 的类型由switch-case 或instanceof 知道,所以转换可以自动完成,不是吗?也许我只是提供一个过于简单的示例,实现请求的功能并不适合更复杂的代码。
【问题讨论】:
-
据我了解您建议
something对象应自动转换为适当的Number子类? -
没错。问题是,如果我遗漏了什么。
标签: groovy switch-statement type-inference instanceof compile-static