开发者

Kotlin Take within Apply scope not working in android

So, I have a nullable Int that I need to use to truncate a list with "take". B开发者_JAVA百科ut when I do this, the list stays the same. Example:

var num: Int? = 1

var list = listOf("1", "2", "3")

// list remains as size 3
var newList = list.apply{
    num?.let {
        this.take(it)
    }
}


This is perfectly normal, because take doesn't modify the input list; it returns a new copy of the selected elements.

The simplest way to write this code is:

val newList = if (num != null) list.take(num) else list


The problem with your code isn't just that take returns a new list (that's true) but that you're using apply as scope function. apply returns this and not the result of the lambda, so no matter what you do in the lambda, newList will always be list.

The proposed solution is a good one. If you're a fan of scope functions you can also do

val newList = num?.let { list.take(it) } ?: list

which is exactly 7 character shorter than

val newList = if (num != null) list.take(num) else list
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜