@CompileStatic
으로 아래 코드를 컴파일 할 수 있습니까?@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
에 의해 알려져있다 무언가의 유형 없음 ? 어쩌면 너무 간단한 예제 만 제시하고 요청 된 기능을 구현하는 것이 더 복잡한 코드에는 적합하지 않을 수도 있습니다.
내가 아는 한 당신은'무언가'객체가 적절한'Number' 서브 클래스에 자동으로 캐스팅되어야한다고 제안 했습니까? – Opal
정확히. 제가 뭔가를 놓친다면 문제가됩니다. –