Kotlin library useful functions

Kaushal Vasava
6 min readDec 21, 2023

--

I will show you some functions of the Kotlin library to make your code clean, maintainable and readable.

To understand this topic, let’s we consider

Shape data class:

Shape( val id: Int, val name: String)

and listOfShape

val listOfShape = listOf(Shape(1,"Triangle"), Shape(2,"Circle"), Shape(3, "Square"), Shape(4,"Rectangle"))

indexOfFirst:

Returns index of the first element in a List, Set or Map matching the given predicate or condition, or -1 if the list does not contain such element.

val shapeName = "Square"  
val indexOfElement: Int = listOfShape.indexOfFirst {
it.name == shapeName // check condition: if name of shape is "Square" or not
}

Here in this example, if name of any shape is equal to “Square” then it will return index of first element else, it will return -1.

find:

Returns the first element(object) in a List, Set or Map matching the given predicate or condition, or null if no such element was found.

val shapeName = "Square"  
val shape: Shape? = listOfShape.first{
it.name == shapeName // check condition: if name of shape is "Square" or not
}

Here in this example, if name of any shape is equal to “Square” then it will return that Shape object else, it will return null.

any:

Returns Boolean as true if at least one element in List, Set or Map matches the given predicate or condition.

val shapeName = "Square"  
val hasSquareElement: Boolean = listOfShape.any {
it.name == shapeName // check condition: if name of shape is "Square" or not
}

Here in this example, if name of any shape is equal to “Square” then it will return true else, it will return false.

Output: hasSquareElement = true

because listOfShape contains Square shape.

none:

Return Boolean as true if none of the items in a List, Set or Map confirms that predicate or condition, else return false.

val shapeName = "Square"  
val isNotSquare: Boolean = listOfShape.none {
it.name == shapeName // check condition: if name of shape is "Square" or not
}

Here in this example, if name of all shapes is not equal to “Square” then it will return true else, it will return false.

Output: isNotSquare = false

because one element of listOfShape is Square shape.

all:

Return Boolean as true if all of the items in a List, Set or Map confirms that predicate or condition, else return false. (Opposite of none)

val shapeName = "Square"  
val hasSameName: Boolean = listOfShape.all {
it.name == shapeName // check condition: if name of shape is "Square" or not
}

Here in this example, if name of all shapes is equal to “Square” then it will return true else, it will return false.

Output: hasSameName = false

because not all element of listOfShape has “Square” name.

count:

Returns the number of elements in this collection.

val totalElement: Int = listOfShape.count()

Output: totalElement = 4

because listOfShape has total 4 elements.

and Returns the number of elements matching the given predicate.

val shapeName = "Square"
val totalSquareElement: Int= listOfShape.count {
it.name == shapeName // check condition: if name of shape is "Square" or not
}

Output: totalSquareElement = 1

because listOfShape has only 1 “Square” shape element.

fold:

The fold function is used to accumulate values starting with an initial value and applying an operation from left to right to the current accumulator value and each element in the collection. If the collection is empty, it returns the specified initial value.

Here’s an example:

// Define a list of numbers
val numbers = listOf(1, 2, 3, 4, 5)

// Using fold to calculate the sum of the numbers starting with an initial value of 0
val sum = numbers.fold(0) { acc, element ->
// The operation is adding the current element to the accumulator
acc + element
}

// Print the result
println("Sum of numbers: $sum")

In this example, the fold function starts with an initial value of 0. The operation provided is a lambda function that takes the current accumulator value (acc) and an element from the list (element), and it calculates the next accumulator value by adding the element to the accumulator.

Output: Sum of numbers: 15

Here’s how the fold works step by step:

  1. Initial accumulator value (acc) is 0.
  2. For the first element (1), the operation adds 1 to the accumulator (0 + 1 = 1).
  3. For the second element (2), the operation adds 2 to the accumulator (1 + 2 = 3).
  4. This process continues until all elements are processed, resulting in the final sum.

foldIndexed:

The foldIndexed function is similar to fold, but it provides an additional index parameter to the operation. It accumulates values starting with an initial value and applies an operation from left to right, taking into account both the current accumulator value, the current element, and its index.

Here’s an example:

// Define a list of words
val words = listOf("apple", "banana", "cherry")

// Using foldIndexed to concatenate words with their index
val result = words.foldIndexed("") { index, acc, element ->
// The operation is concatenating the current element with its index to the accumulator
acc + "[$index: $element] "
}

// Print the result
println("Result: $result")

In this example, the foldIndexed function starts with an initial accumulator value of an empty string. The operation provided is a lambda function that takes three parameters: the current index (index), the current accumulator value (acc), and an element from the list (element). The operation concatenates the current element with its index in square brackets and adds it to the accumulator.

Output: Result: [0: apple] [1: banana] [2: cherry]

Here’s how the foldIndexed works step by step:

  1. Initial accumulator value (acc) is an empty string.
  2. For the first element (“apple”) at index 0, the operation adds “[0: apple] “ to the accumulator.
  3. For the second element (“banana”) at index 1, the operation adds “[1: banana] “ to the accumulator.
  4. For the third element (“cherry”) at index 2, the operation adds “[2: cherry] “ to the accumulator.
  5. The final result is the concatenated string with elements and their respective indices.

slice:

The slice function is used to extract a sublist from a collection based on the specified indices. It returns a new list containing elements from the original collection at the specified indices.

Here’s an example:

// Define a list of numbers
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)

// Using slice to extract elements at indices 2, 4, and 6
val result = numbers.slice(listOf(2, 4, 6))

// Print the result
println("Result: $result")

In this example, the slice function is applied to the numbers list. The argument passed to slice is a list of indices (2, 4, and 6). The function creates a new list containing elements at those specified indices from the original list.

Output: Result: [3, 5, 7]

Here’s how the slice function works in this example:

  1. The element at index 2 in the original list is 3.
  2. The element at index 4 in the original list is 5.
  3. The element at index 6 in the original list is 7.
  4. The slice function returns a new list [3, 5, 7] containing these elements.

You can use slice with various collections like lists, arrays, etc., and you can specify any combination of indices to extract the desired elements.

There are more functions you can check out _Collections.kt file in your project.

Thank you for reading. 🙌🙏✌.

Don’t forget to clap 👏 to support me and follow me for more such useful articles about Android Development, Kotlin & KMP.

If you need any help related to Android, Kotlin and KMP. I’m always happy to help you.

Follow me on:

Medium, LinkedIn, Twitter, GitHub, and Instagram.

--

--

Kaushal Vasava

Android Developer | Kotlin | Jetpack Compose | Kotlin MultiPlatform | LinkedIn's Top Voice (3K+ Followers) | Apps with 100K+ Downloads on the Playstore