Groovy @CompileStatic:是否可以进行自动类型转换?
是否可以使用Groovy @CompileStatic:是否可以进行自动类型转换?,groovy,switch-statement,type-inference,instanceof,compile-static,Groovy,Switch Statement,Type Inference,Instanceof,Compile Static,是否可以使用@CompileStatic编译以下代码 import groovy.transform.CompileStatic @CompileStatic class CompileStaticTest { List<Number> numbers = [] void addWithCase(something) { switch (something) { case Integer: numbers <<
@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
}
}
}
当前存在编译错误:
[Static type checking] - Cannot call <T> java.util.List <Number>#leftShift(T) with arguments [java.lang.Object]
[静态类型检查]-无法使用参数[java.lang.Object]调用java.util.List#leftShift(T)
通过开关盒或实例知道某物的类型,因此可以自动进行转换,不是吗?也许我只是给出了一个太简单的示例,实现所请求的功能不适合更复杂的代码。这听起来像是一个bug,因为允许以下情况:
if (something instanceof Integer) {
something.intValue()
}
也许填写一个?据我所知,您建议将
某个对象自动强制转换为适当的编号子类?准确地说。问题是,如果我遗漏了什么,我不认为这是一个bug,而是@CompileStatic
的一个新功能。目前还不清楚已经支持什么。因此,我不想申请新的罚单,而是想先看看它是否可行。
if (something instanceof Integer) {
something.intValue()
}