Kotlin String all()

Kotlin String all() Tutorial

The all() function in Kotlin is used to check whether all characters in the string satisfy the given predicate. It returns true if all characters match the predicate, and false otherwise.

In this tutorial, we’ll explore the syntax of the all() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the all() function is as follows:

fun CharSequence.all(
    predicate: (Char) -> Boolean
): Boolean

where

ParameterDescription
predicateA lambda function that takes a character as an argument and returns true or false.
Parameter of String all() function

The all() function applies the given predicate to each character of the string. If all characters satisfy the predicate, the function returns true; otherwise, it returns false.

Examples for String all() function

1. Checking if All Characters are Digits

In this example, we’ll use all() to check if all characters in a string are digits.

  1. Take a string value in numericString.
  2. Define a predicate function that checks if a character is a digit.
  3. Call all() function on numericString with the defined predicate. The function returns true if all characters are digits, and false otherwise.
  4. You may print the result to the console output.

Kotlin Program

fun main() {
    val numericString = "12345"

    // Using all() to check if all characters are digits
    val allDigits = numericString.all { it.isDigit() }

    // Printing the original string and the result
    println("Numeric String: $numericString")
    println("All Digits: $allDigits")
}

Output

Numeric String: 12345
All Digits: true

2. Checking if All Characters are either ‘a’, ‘b’, or ‘c’

In this example, we’ll use all() to check if all characters in a string are ‘a’, ‘b’, and/or ‘c’.

  1. Take a string value in myString.
  2. Define a predicate function that checks if a character is ‘a’, ‘b’, or ‘c’.
  3. Call all() function on myString with the defined predicate. The function returns true if all characters are ‘a’, ‘b’, or ‘c’, false otherwise.
  4. Use the returned value as a condition in if else statement, and print the output to console.

Kotlin Program

fun main() {
    val myString = "abbcabaabacb"

    // Using all()
    if (myString.all { it == 'a' || it == 'b' || it == 'c' }) {
        println("The string contains only a,b, and c.")
    } else {
        println("There are characters other than a,b, and c.")
    }
}

Output

The string contains only a,b, and c.

Summary

In this tutorial, we’ve covered the all() function in Kotlin strings, its syntax, and how to use it to check if all characters in a string satisfy a given predicate. This function provides a convenient way to perform a condition check on all characters within a string.