将Java转换为Kotlin代码时出错

所以这是我的Java代码工作

if (currentForecastJava.getCurrentObservation().getTempF() >= 60) { mCurrentWeatherBox.setBackgroundColor(getResources().getColor(R.color.weather_warm)); mToolbar.setBackgroundColor(getResources().getColor(R.color.weather_warm)); } else { mCurrentWeatherBox.setBackgroundColor(getResources().getColor(R.color.weather_cool)); mToolbar.setBackgroundColor(getResources().getColor(R.color.weather_cool)); } 

我想要做的是写在Kotlin(知道AS有转换器,但不会改变任何东西)

 if (currentObservationKotlin.tempF.compareTo() >=) currentWeatherBox.setBackgroundColor(resources.getColor(R.color.weather_warm)) toolbar.setBackgroundColor(resources.getColor(R.color.weather_warm)) else currentWeatherBox.setBackgroundColor(resources.getColor(R.color.weather_cool)) toolbar.setBackgroundColor(resources.getColor(R.color.weather_cool)) 

我知道我需要一个值在compareTo()和后,但我不知道该怎么做,因为我想比较TempF为60,因为我希望根据数据类的TempF值更改颜色。 我没有另一个对象来比较它。

我可以用Java编写这个程序,它可以与Kotlin代码的其余部分一起工作,但是试图看看Kotlin是否能够使Java如果/ else相似并且更快写入。

Java和Kotlin版本几乎是一样的。 从Java代码开始,放下分号; 那么任何可以为空的东西都需要用null检查来处理,或者你断言它们永远不会是空的!! ,或者使用另一个null操作符。 你没有显示足够的代码(即进入这个代码的方法签名,或所使用的变量的声明)来确切地告诉你需要改变什么。

为了处理null值,请参阅: 在Kotlin中,处理可空值的惯用方法是什么?

你最终可能会将调用setter方法的警告称为something.setXyz(value)而不是将其指定为属性something.xyz = value ,IDE将帮助您解决这些问题,或者您可以接受警告。

有关JavaBean属性的互操作性的更多信息,请参阅: Java Interop:Getters和Setter

因此,考虑到所有这一切,最终的代码(多一点清理)可能会出现如下所示:

 val currentTemp = currentForecastJava.getCurrentObservation()?.getTempF() ?: -1 // or change -1 to whatever default you want if there is no observation if (currentTemp >= 60) { val warmColor = getResources().getColor(R.color.weather_warm) mCurrentWeatherBox.backgroundColor = warmColor mToolbar.backgroundColor = warmColor } else { val coolColor = getResources().getColor(R.color.weather_cool) mCurrentWeatherBox.backgroundColor = coolColor mToolbar.backgroundColor = coolColor }