Kotlin List filterIsInstance()
Syntax & Examples
Syntax of List.filterIsInstance()
There are 2 variations for the syntax of List.filterIsInstance() extension function. They are:
1.
fun <R> Iterable<*>.filterIsInstance(): List<R>
This extension function returns a list containing all elements that are instances of specified type parameter R.
2.
fun <R> Iterable<*>.filterIsInstance( klass: Class<R> ): List<R>
This extension function returns a list containing all elements that are instances of specified class.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing elements of different types. - We use the
filterIsInstance
function onlist1
to filter only elements of typeString
. - The result, which is a list of strings, is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, "hello", 3.14, true, 'c')
val result = list1.filterIsInstance<String>()
println(result)
}
Output
[hello]
2 Example
In this example,
- We create a list named
list2
containing elements of different types. - We use the
filterIsInstance
function onlist2
to filter only elements of typeChar
. - The result, which is a list of characters, is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf("apple", 123, "banana", 'x', false)
val result = list2.filterIsInstance<Char>()
println(result)
}
Output
[x]
3 Example
In this example,
- We create a list named
list3
containing elements of different types. - We use the
filterIsInstance
function onlist3
to filter only elements of typeInt
. - The result, which is a list of integers, is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf(1.5, true, 10, 'a', "world")
val result = list3.filterIsInstance<Int>()
println(result)
}
Output
[10]
Summary
In this Kotlin tutorial, we learned about filterIsInstance() extension function of List: the syntax and few working examples with output and detailed explanation for each example.