Server Side Kotlin-13

Server Side Kotlin-13

·

2 min read

To check the presence of an element in a collection, use the contains() function. It returns true if there is a collection element that equals() the function argument. You can call contains() in the operator form with the in keyword.

To check the presence of multiple instances together at once, call containsAll() with a collection of these instances as an argument.

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" )  
println(games.contains("godot"))
println("hipreme Engine " in games)

println(games.containsAll(listOf("godot", "bevy")))
println(games.containsAll(listOf("unity", "hipreme Engine ")))

output:-

true false true false

Additionally, you can check if the collection contains any elements by calling isEmpty() or isNotEmpty()

val games = listOf("unity", "unreal", "godot", "bevy", "monogame", "supe rgame" ) 
println(games.isEmpty())
println(games.isNotEmpty())

val gameempty = emptyList<String>()
println(gameempty.isEmpty())
println(gameempty.isNotEmpty())

output:

false true true false

If you need to map the collection before retrieving the element, there is a function firstNotNullOf(). It combines 2 actions:

Maps the collection with the selector function

Returns the first non-null value in the result

In Kotlin, the firstNotNullOf() function is used to obtain the first non-null value produced by a transformation function applied to elements of a collection in iteration order. If no non-null result is found, it throws a NoSuchElementException. This function is useful when you want to transform elements and retrieve the first non-null result.

val numbers = listOf(15, 2, 13, 4, 5)
val firstOddSquare = numbers.firstNotNullOf { if (it % 2 != 0) it * it else null }

println("First square of an odd number: $firstOddSquare")

output:

First square of an odd number: 225