2017-06-02 82 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

我只創建了其他變量,以使代碼更清晰地說明哪些步驟正在做什麼。它們是可選的。 –