filter所在位置是kotlin.text.filter,其相關用法介紹如下。

用法一

inline fun CharSequence.filter(
    predicate: (Char) -> Boolean
): CharSequence

返回一個 char 序列,其中僅包含原始 char 序列中與給定 predicate 匹配的那些字符。

例子:

import java.util.Locale
import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val text = "a1b2c3d4e5"

val textWithOnlyDigits = text.filter { it.isDigit() }

println(textWithOnlyDigits) // 12345
//sampleEnd
}

輸出:

12345

用法二

inline fun String.filter(
    predicate: (Char) -> Boolean
): String

返回一個字符串,該字符串僅包含原始字符串中與給定 predicate 匹配的那些字符。

例子:

import java.util.Locale
import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val text = "a1b2c3d4e5"

val textWithOnlyDigits = text.filter { it.isDigit() }

println(textWithOnlyDigits) // 12345
//sampleEnd
}

輸出:

12345