Server Side Kotlin-19

Server Side Kotlin-19

·

1 min read

List Operations

If the list size is less than the specified index, an exception is thrown. However two functions can avoid such exception.
getOrElse():It calculate the default value to return if the index is absent in the collection.
getOrNull(): returns null as the default value.

val numbers = listOf(11, 22, 33, 44)
println(numbers.getOrNull(5))             // null
println(numbers.getOrElse(5, {it}))        // 5

output:-
null
5

subList() function gives elements as a list from a give range.

val numbers = (10..23).toList()
println(numbers.subList(2, 4))

outuput:
[12, 13]

Position of an element can be get by indexOf() and lastIndexOf(). They return the first and the last position of an element . If elements is not found , both functions return -1.

val numbers = listOf(11, 22, 33, 44, 25, 56)
println(numbers.indexOf(3))
println(numbers.lastIndexOf(3))

ouput:-
-1

-1