Kotlin String asSequence()

Kotlin String asSequence() Tutorial

The asSequence() function in Kotlin is used to convert a string into a sequence of characters.

The asSequence() function allows you to treat a string as a sequence, enabling the use of sequence operations for efficient and lazy processing of its elements.

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

Syntax

The syntax of the asSequence() function is simple:

fun CharSequence.asSequence(): Sequence<Char>

The asSequence() function returns a sequence of characters, allowing you to perform sequence operations on the original string.

Examples for String asSequence() function

1. Filtering and Mapping Characters

In this example, we’ll use asSequence() along with sequence operations to filter and map characters in a string.

  1. Take a string value in word.
  2. Call asSequence() function on word to convert it into a sequence.
  3. Use sequence operations like filter() to include only specific characters and map() to transform each character.
  4. You may print the result of the sequence operations to the console output.

Kotlin Program

fun main() {
    val word = "Kotlin"

    // Using asSequence() and sequence operations
    val result = word.asSequence()
        .filter { it.isLetter() }
        .map { it.uppercaseChar() }

    // Printing the result
    println("Filtered and Mapped Characters: ${result.toList()}")
}

Output

Filtered and Mapped Characters: [K, O, T, L, I, N]

2. Lazily Evaluating Operations

In this example, we’ll demonstrate the lazy evaluation nature of sequences using asSequence().

  1. Take a string value in sentence.
  2. Call asSequence() function on sentence to convert it into a sequence.
  3. Perform multiple sequence operations, including filter() and map().
  4. Print the result after each operation to observe the lazy evaluation.

Kotlin Program

fun main() {
    val sentence = "Kotlin is expressive and concise."

    // Using asSequence() for lazy evaluation
    val result = sentence.asSequence()
        .filter { it.isLetter() }
        .map { it.uppercaseChar() }
        .filter { it != 'L' }

    // Printing the result after each operation
    println("Filtered Characters: ${result.toList()}")
}

Output

Filtered Characters: [K, O, T, I, N, I, S, E, X, P, E, C, T, I, V, E, A, N, D, C, O, N, C, I, S, E]

Summary

In this tutorial, we’ve covered the asSequence() function in Kotlin strings, its syntax, and how to use it to treat a string as a sequence of characters. This function allows for efficient and lazy processing of string elements using powerful sequence operations.