下面的代码可以编译@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]
某些东西的类型是已知的,switch-case
所以instanceof
演员可以自动完成,不是吗?也许我只是提供了一个过于简单的示例,并且实现所请求的功能不适合更复杂的代码。