首页 > 其他 > 详细

[Kotlin] The Let function

时间:2020-10-28 21:04:40      阅读:34      评论:0      收藏:0      [点我收藏+]

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)} ?: ""
    }

 

[Kotlin] The Let function

原文:https://www.cnblogs.com/Answer1215/p/13893387.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!