[Kotlin] The Elvis operator

In Javascript, we have:

return age === null ? -1 : age

In kotlin, we can do the same thing with a better / simpler syntax:

    val safeAge: Int
        get() = age ?: -1 // if age is null return -1 otherwise return age

  

Let's see another use case:

// javascript

let favoriteColor = null

function getUpperFavoriteColor () {
    if(favoriteColor === null) return ""
    else 
        return favoriteColor.toUpperCase()]
}
// kotlin

var favoriteColor: String?

fun getUpperFavoriteColor() {
    return favoriateColor?.toUpperCase() ?: ""
}
原文地址:https://www.cnblogs.com/Answer1215/p/13893279.html