Kotlin String asIterable()

Kotlin String asIterable() Tutorial

The asIterable() function in Kotlin is used to convert a string into an iterable of characters.

String asIterable() allows you to treat a string as a sequence of individual characters, making it convenient for operations that require iterating over each character.

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

Syntax

The syntax of the asIterable() function is:

fun CharSequence.asIterable(): Iterable<Char>

The asIterable() function returns an iterable of characters, allowing you to iterate over each character in the original string.

Examples for String asIterable() function

1. Iterating Over Characters

In this example, we’ll use asIterable() to iterate over each character in a string and print them individually.

  1. Take a string value in sampleString.
  2. Call asIterable() function on sampleString. The function returns an iterable of characters.
  3. Use a For loop to iterate over the characters and print each character to the console output.

Kotlin Program

fun main() {
    val sampleString = "Kotlin"

    // Using asIterable() to iterate over characters
    val charIterable = sampleString.asIterable()

    // Printing each character
    println("Characters in $sampleString:")
    for (char in charIterable) {
        println(char)
    }
}

Output

Characters in Kotlin:
K
o
t
l
i
n

2. Using Iterable Functions

In this example, we’ll leverage the power of iterable functions on the result of asIterable().

  1. Take a string value in word.
  2. Call asIterable() function on word. The function returns an iterable of characters.
  3. Use iterable functions like map() and filter() on the result to transform and filter characters.
  4. You may print the transformed characters to the console output.

Kotlin Program

fun main() {
    val word = "Kotlin"

    // Using asIterable() and iterable functions
    val result = word.asIterable()
        .map { it.uppercaseChar() }
        .filter { it.isLetter() }

    // Printing the transformed characters
    println("Transformed Characters: ${result.joinToString(", ")}")
}

Output

Transformed Characters: K, O, T, L, I, N

Summary

In this tutorial, we’ve covered the asIterable() function in Kotlin strings, its syntax, and how to use it to treat a string as an iterable of characters. This function opens up possibilities for applying iterable functions and operations on individual characters within a string.