Kotlin List filterIsInstanceTo()
Syntax & Examples


Syntax of List.filterIsInstanceTo()

There are 2 variations for the syntax of List.filterIsInstanceTo() extension function. They are:

1.
fun <R, C : MutableCollection<in R>> Iterable<*>.filterIsInstanceTo( destination: C ): C

This extension function appends all elements that are instances of specified type parameter R to the given destination.

2.
fun <C : MutableCollection<in R>, R> Iterable<*>.filterIsInstanceTo( destination: C, klass: Class<R> ): C

This extension function appends all elements that are instances of specified class to the given destination.



✐ Examples

1 Example

In this example,

  • We create a list named list containing elements of different types: integers, strings, characters, and a double.
  • We create an empty mutable list named result to store filtered integers.
  • We apply the filterIsInstanceTo extension function on list to filter out only the integers and append them to result.
  • Finally, we print the result list to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, "two", 3.0, '4', 5);
    val result = mutableListOf<Int>();
    list.filterIsInstanceTo(result);
    println(result);
}

Output

[1, 5]

2 Example

In this example,

  • We create a list named list containing elements of different types: characters, integers, and strings.
  • We create an empty mutable list named result to store filtered characters.
  • We apply the filterIsInstanceTo extension function on list to filter out only the characters and append them to result.
  • Finally, we print the result list to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 1, 'b', "two", 'c');
    val result = mutableListOf<Char>();
    list.filterIsInstanceTo(result);
    println(result);
}

Output

[a, b, c]

3 Example

In this example,

  • We create a list named list containing elements of different types: strings and integers.
  • We create an empty mutable list named result to store filtered strings.
  • We apply the filterIsInstanceTo extension function on list to filter out only the strings and append them to result.
  • Finally, we print the result list to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", 10, "banana", 20, "orange", 30);
    val result = mutableListOf<String>();
    list.filterIsInstanceTo(result);
    println(result);
}

Output

[apple, banana, orange]

Summary

In this Kotlin tutorial, we learned about filterIsInstanceTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.