Reputation: 1276
So this is my Java code that works
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));
}
What I am trying to do is write this in Kotlin(know AS has the converter but does not change anything)
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))
I know I need a value in the compareTo() and after but I am not really sure what to place as I want to compare TempF to 60 as I want the color to change based on the TempF value from data class. I do not have another object to compare it to.
I can write this in Java and it works with the rest of the Kotlin code but trying to see if Kotlin can make the Java if/else similar and quicker to write.
Upvotes: 1
Views: 229
Reputation: 85936
The Java and Kotlin version would be almost the same. Start with the Java code and drop the semicolons ;
and then anything that COULD be nullable needs to be handled with either null
checks or you asserting that they will never be null with !!
, or using another null
operator. You do not show enough code (i.e. the method signature coming into this code, or the declaration of the used variables) to tell you exactly what needs to change.
For handling null
values see: In Kotlin, what is the idiomatic way to deal with nullable values
You might end up with warnings around calling a setter method as something.setXyz(value)
instead of assigning it as a property something.xyz = value
and the IDE will help you fix those or you can live with the warning.
For more about interoperability with JavaBean properties see: Java Interop: Getters and Setters
So with all of that in mind, your final code (with a little more cleaning) might appear something like:
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
}
Upvotes: 1