Kotlin Set filterIsInstance()
Syntax & Examples


Set.filterIsInstance() extension function

The filterIsInstance() extension function in Kotlin filters elements in a set, returning a list of elements that are instances of the specified type or class.


Syntax of Set.filterIsInstance()

There are 2 variations for the syntax of Set.filterIsInstance() extension function. They are:

1.
fun <R> Set<*>.filterIsInstance(): List<R>

This extension function returns a list containing all elements that are instances of the specified type parameter R.

Returns value of type List<R>.

2.
fun <R> Set<*>.filterIsInstance(klass: Class<R>): List<R>

This extension function returns a list containing all elements that are instances of the specified class.

Returns value of type List<R>.



✐ Examples

1 Filtering instances of String

Using filterIsInstance() to filter elements in a set that are instances of String.

For example,

  1. Create a set containing elements of different types.
  2. Use filterIsInstance() to filter elements that are instances of String.
  3. Print the resulting list.

Kotlin Program

fun main(args: Array<String>) {
    val mixedSet: Set<Any> = setOf(1, "two", 3.0, "four", 5)
    val strings = mixedSet.filterIsInstance<String>()
    println(strings)
}

Output

["two", "four"]

2 Filtering instances of Int

Using filterIsInstance() to filter elements in a set that are instances of Int.

For example,

  1. Create a set containing elements of different types.
  2. Use filterIsInstance() to filter elements that are instances of Int.
  3. Print the resulting list.

Kotlin Program

fun main(args: Array<String>) {
    val mixedSet: Set<Any> = setOf(1, "two", 3.0, 4, 5)
    val integers = mixedSet.filterIsInstance<Int>()
    println(integers)
}

Output

[1, 4, 5]

3 Filtering instances of Double

Using filterIsInstance() to filter elements in a set that are instances of Double.

For example,

  1. Create a set containing elements of different types.
  2. Use filterIsInstance() to filter elements that are instances of Double.
  3. Print the resulting list.

Kotlin Program

fun main(args: Array<String>) {
    val mixedSet: Set<Any> = setOf(1, "two", 3.0, 4, 5)
    val doubles = mixedSet.filterIsInstance<Double>()
    println(doubles)
}

Output

[3.0]

Summary

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