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

用法一

inline fun CharSequence.filterIndexed(
    predicate: (index: Int, Char) -> Boolean
): CharSequence

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

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val numbers: List<Int> = listOf(0, 1, 2, 3, 4, 8, 6)
val numbersOnSameIndexAsValue = numbers.filterIndexed { index, i -> index == i }

println(numbersOnSameIndexAsValue) // [0, 1, 2, 3, 4, 6]
//sampleEnd
}

輸出:

[0, 1, 2, 3, 4, 6]

參數

predicate- 獲取字符索引和字符本身並返回該字符的謂詞評估結果的函數。

用法二

inline fun String.filterIndexed(
    predicate: (index: Int, Char) -> Boolean
): String

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

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val numbers: List<Int> = listOf(0, 1, 2, 3, 4, 8, 6)
val numbersOnSameIndexAsValue = numbers.filterIndexed { index, i -> index == i }

println(numbersOnSameIndexAsValue) // [0, 1, 2, 3, 4, 6]
//sampleEnd
}

輸出:

[0, 1, 2, 3, 4, 6]

參數

predicate- 獲取字符索引和字符本身並返回該字符的謂詞評估結果的函數。