【问题标题】:@CompileStatic: automatic type cast possible?@CompileStatic:可以进行自动类型转换吗?
【发布时间】: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


【解决方案1】:

这听起来像是一个错误,因为以下是允许的:

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

也许填写JIRA?

【讨论】:

  • 我不认为这是一个错误,而是@CompileStatic 的一个新功能。目前还不清楚已经支持什么。因此,与其提交新票,我首先想检查一下是否可行。
猜你喜欢
  • 1970-01-01
  • 2016-05-07
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
相关资源
最近更新 更多