gpt4 book ai didi

kotlin - Kotlin空安全容器”是一种可变属性,该属性可能已在此时更改

转载 作者:行者123 更新时间:2023-12-02 13:22:26 25 4
gpt4 key购买 nike

class ExchangeRatesServiceImpl : ExchangeRatesService {

private var container: ExchangeRatesContainer? = null

/**
* {@inheritDoc}
*/
override val currentRates: Map<Currency, BigDecimal>
get() {
if (container == null || container.date != LocalDate.now()) {
container = client.getRates(Currency.getBase())
log.info("exchange rates has been updated: {}", container)
}
return ImmutableMap.of<Currency, BigDecimal>(
Currency.EUR, container.rates[Currency.EUR.name],
Currency.RUB, container.rates[Currency.RUB.name],
Currency.USD, BigDecimal.ONE
)
}
}

如果(容器== null || container.date!= LocalDate.now())行
错误【因为“容器”是可变属性,而这一次可能已经更改了)

我该如何编译?

最佳答案

container在函数范围之外声明,因此从理论上讲,在检查null然后使用它之间,另一个线程可以修改它。为了防止这种情况,您应该创建一个初始化为container的局部变量,并像这样使用它:

class ExchangeRatesServiceImpl : ExchangeRatesService {

private var container: ExchangeRatesContainer? = null

/**
* {@inheritDoc}
*/
override val currentRates: Map<Currency, BigDecimal>
get() {
val tempContainer = container
if (tempContainer == null || tempContainer.date != LocalDate.now()) {
tempContainer = client.getRates(Currency.getBase())
log.info("exchange rates has been updated: {}", tempContainer)
}
return ImmutableMap.of<Currency, BigDecimal>(
Currency.EUR, container.rates[Currency.EUR.name],
Currency.RUB, container.rates[Currency.RUB.name],
Currency.USD, BigDecimal.ONE
)
}
}

关于kotlin - Kotlin空安全容器”是一种可变属性,该属性可能已在此时更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53018369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com