2017-06-02 84 views
1

所以这是我的Java代码,工程错误转换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)); 
} 

我所试图做的是在科特林写(知道的有转换器,但不会改变任何东西)

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()和after后面的值,但我不确定要放置什么,因为我想将TempF与60进行比较,因为我希望颜色根据数据类中的TempF值进行更改。我没有另一个对象来比较它。

我可以用Java写,并将其与科特林其余代码工作,但想看看是否科特林可以在Java的if/else相似,更快地写。

+0

为什么不只是'currentObservationKotlin.tempF> = 60'? – hotkey

+0

我可以使用currentObservationKotlin.tempF! > = 60,一切都按预期进行编译和工作,但不知道为什么我需要放!!仍然试图用Kotlin学习无用的东西。 –

+0

当我按照上面的建议进行操作时,出现> =操作符的错误。我声明:“以下函数都不能用所提供的参数调用:public final operator fun compareTo(other:Double):int在kotlin中定义。”double“。我可以使用currentObservationKotlin.tempF! > = 60,一切都按预期进行编译和工作,但不知道为什么我需要放!!仍然试图用Kotlin学习无用的东西。 –

回答

1

的Java和科特林版本是几乎相同。从Java代码开始,删除分号;,然后任何可能为空的需要使用null检查来处理,或者声明它们将永远为空,并且使用!!或使用其他null运算符。您不会显示足够的代码(即进入该代码的方法签名或所使用变量的声明),以准确告诉您需要更改哪些内容。

如需办理null值看:In Kotlin, what is the idiomatic way to deal with nullable values

你可能有警告最终各地调用setter方法为​​,而不是分配给它作为一个属性something.xyz = value和IDE会帮你解决这些或者你可以住与警告。

欲了解更多有关使用JavaBean属性的互操作性看到:Java Interop: Getters and Setters

因此,所有的考虑到这一点,您的最终代码(多一点清洁)可能会出现这样的:

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 
} 
+0

真棒,非常感谢你,将考虑这两个链接。我也看到你使用猫王操作员。我试图首先这样做,但无法正确创建代码。用Kotlin创建另一个val/car,然后使用var currentTemp:Double = currentObservationKotlin?.tempF!并将其设置为TextView? –

+0

我只创建了其他变量,以使代码更清晰地说明哪些步骤正在做什么。它们是可选的。 –