我有一個項目變量datePurchased
,它可以爲空。根據購買日期,我生成一個標籤。當我檢查datePurchased是否爲null時,在其他分支中,我仍然需要檢查null。它說聰明的演員是不可能的,因爲它是一個可變的財產。Kotlin檢查空兩次,否則
這裏是我試過到目前爲止:
if (datePurchased == null) {
""
} else {
if (datePurchased.isToday()) {//error here
}
}
when {
datePurchased == null -> {
}
datePurchased.isToday() -> {//smart cast bla bla mutable bla bla
datePurchased?.isToday() -> {//expected Boolean, got Boolean?
datePurchased?.isToday()?:false -> {//all good, but does not look nice, since datePurchased can't be null here
}
else -> {
}
}
可能的重複[最好的方式來處理這種情況下,「智能轉換是不可能的」](http://stackoverflow.com/questions/39246249/best-way-to-handle-such-scenario-where-smart- cast-is-imposible) – miensol
@miensol所以,你在暗示我的else分支應該被「包裹」在'?.let'中? –
是的。你可以這樣做:'datePurchased?.let {if(it.isToday())//做點什麼}?:「」' – marstran