Server Side Kotlin-12

Server Side Kotlin-12

·

2 min read

elementAt() retrieving an element at a specific position. It can be call with integer number as an argument, and it will give the collection element at the given position.

elementAt() is useful for collections where there is no indexed access, or are statically unknown to provide one.

val games = linkedSetOf("unity", "unreal", "godot", "bevy", "monogame", "supergame" )
println(games.elementAt(3))
val gamesSortedSet = sortedSetOf("unity", "unreal", "godot", "bevy", "monogame", "supergame")
println(gamesSortedSet.elementAt(0)) // elements are stored in the ascending order

output:-

bevy

bevy

During collection element retrieval, exception can be avoided by using another version of elementAt():

elementAtOrNull() returns null when the specified position is out of the collection bounds.

elementAtOrElse() additionally takes a lambda function which maps an Int argument to an instance of the collection element type. When called with an out-of-bounds position, the elementAtOrElse() returns the result of the lambda on the given value.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" )  
println(games.elementAtOrNull(5))
println(games.elementAtOrElse(5) { index -> "The value for index $index is undefined"})

outut:

supe rgame

supe rgame

Functions first() and last() try to search a collection for elements matching a given predicate. function first() uses a predicate which tests a collection element, and gives the first element on which the predicate yields true. Reciprocally , last() using predicate returns the last match element.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supergame" ) 
println(games.first { it.length > 4 })
println(games.last { it.startsWith("u") })

output:

unity

unreal

If no elements match the predicate, both above functions throw exceptions. To avoid them, use firstOrNull() and lastOrNull() instead: they return null if no matching elements are found.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supergame" ) 
println(games.firstOrNull { it.length > 9 })  
or   use find(), which is an alias.
println(games.find { it.length > 9 })

to retrieve an arbitrary element of a collection, use the random() function. random() can be call without arguments

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supergame" ) 
println(games.random())

output:

bevy

output:

null