So, I have a nullable Int that I need to use to truncate a list with "take". But 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)
}
}
CodePudding user response:
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
CodePudding user response:
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
