[Kotlin] The Let function

Let function is another way to solve null problem in kotlin.

 

When you have such problem:

var favoriteColor: String? = null
...
...
return
if f(avoriteColor !== null) getLastLetter(favoriteColor) else ""

The problem is 'favoriteColor' might change, so smart casting is complaining about this.

 

The way to solve the problem is using let function.

val hello = "Hello World"
val uppercaseHello = hello.toUpperCase()
var uppercaseHello = hello.let {x -> x.toUpperCase()}
var uppercaseHello = hello.let {it.toUpperCase()}

 

Solution:

    var favoriteColor: String? = null
    fun getLastLetter(a: String) = a.takeLast(1)

    fun getLastLetterOfColor(): String {
        favoriteColor?.let {getLastLetter(it)} ?: ""
    }

 

posted @ 2020-10-28 20:54  Zhentiw  阅读(62)  评论(0)    收藏  举报