@CompileStatic: automatic type cast possible?

291 Views Asked by At

Is it possible that the below code can be compiled with @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
        }
    }   
}

Usage:

test = new CompileStaticTest()

test.addWithCase(11)
test.addWithCase(12f)
test.addWithCase('13')

test.addWithInstanceof(21)
test.addWithInstanceof(22f)
test.addWithInstanceof('23')

println test.numbers

Currently there are compile errors:

[Static type checking] - Cannot call <T> java.util.List <Number>#leftShift(T) with arguments [java.lang.Object]

The type of something is known by switch-case or instanceof so the cast could be done automatically, no? Maybe I am just presenting a too simple example and implementing the requested functionality is not suitable for more complex code.

1

There are 1 best solutions below

1
On

This sounds like a bug, because the following is allowed:

if (something instanceof Integer) {
    something.intValue()
}

Maybe filling a JIRA?