Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Kotlin Standard Library: Common Functions

Introduction to Common Functions

The Kotlin Standard Library offers a rich set of functionalities in the form of common functions that simplify various programming tasks. These functions are designed to be intuitive and efficient, allowing developers to carry out common operations with minimal code.

1. Collection Functions

Kotlin provides a variety of collection functions that can be utilized on lists, sets, and maps. These functions allow you to transform, filter, and aggregate data collections easily.

Example: Filtering a List

Code:

val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }

Output:

[2, 4]

In this example, we create a list of numbers and filter it to obtain only the even numbers.

2. String Functions

Kotlin also includes a comprehensive set of functions to manipulate strings. These functions help in performing operations such as searching, replacing, and transforming string values.

Example: Replacing a Substring

Code:

val original = "Hello, World!"
val modified = original.replace("World", "Kotlin")

Output:

Hello, Kotlin!

Here, we replace the substring "World" with "Kotlin" using the replace function.

3. Mathematical Functions

The Kotlin Standard Library includes mathematical functions that enable calculations such as finding maximum, minimum, and rounding numbers, among others.

Example: Finding the Maximum

Code:

val maxNumber = maxOf(10, 20, 30)

Output:

30

In this example, we use the maxOf function to find the maximum value among the provided numbers.

4. Higher-Order Functions

Higher-order functions are functions that take other functions as parameters or return them. Kotlin supports lambda expressions, making it easy to work with higher-order functions.

Example: Using a Higher-Order Function

Code:

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
  return operation(a, b)
}
val sum = calculate(5, 10, { x, y -> x + y })

Output:

15

In this example, we define a higher-order function `calculate` that takes two integers and a function as parameters. We use it to sum two numbers.

Conclusion

The Kotlin Standard Library's common functions greatly enhance productivity and code readability. By utilizing these built-in functions, developers can write cleaner and more efficient code, effectively reducing the need for boilerplate.