【问题标题】:Why can't I directly assign to object properties using multiple return values from a method?为什么我不能使用方法的多个返回值直接分配给对象属性?
【发布时间】:2014-07-24 08:57:41
【问题描述】:

根据this 问题,我编写了以下代码,这会引发编译时错误:

代码如下:

43. Currency currency = new Currency()
44. (currency.rate_one, currency.time_one) = getDateAndRate()

我的方法有两个返回值:

def getDateAndRate(){
    Date date = new Date()
    double rate = getRate();
    return [rate, date]
}

抛出错误

expecting '}', found ',' @ line 44, column 26.
(currency.rate_one, currency.time_one) = getDateAndRate()
                  ^

【问题讨论】:

    标签: groovy return return-value


    【解决方案1】:

    试试这个

    def (rate, time) = getDateAndRate()
    currency.rate_one = rate
    currency.time_one = time
    

    【讨论】:

    • 有效!但为什么它不像上面那样工作?好烦
    • 如果你想让这段代码不那么冗长,你可以更改getDateAndRate 以接受Currency 参数,在方法中更新它,然后返回它
    【解决方案2】:

    有一个技巧是我最近才学会的,那就是将多重赋值和与:

    with (currency) {
        (rate_one, time_one) = getDateAndTime()
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      相关资源
      最近更新 更多