Kotlin高级特性:3、集合操作符

Kotlin 集合操作符

基本上 RxJava 中支持的操作符,在 Kotlin 中都可以找到。

代码示例

fun main(args: Array) {
    val a:Array = arrayOf("4","d","e","q","s","g","5","0","i","9")

    val index:Array = arrayOf(5,3,4,9,1,2,6,8,7,10,3,11,5,12)


    index.filter {
        it < a.size // 过滤掉index数组中大于a的长度的元素
    }.map {
        a[it]   //做一次变换:取出a数组中it下标的元素
                //it 就是index进行过滤后,对剩下所有元素进行遍历时的临时变量
    }.reduce { s, s1 ->
        "$s$s1" //将两个值合并成一个值
    }.also {
        println("结果:$it") //使用 also 输出结果
    }
}

拓展函数简单示例

fun show(){
    val list:List = listOf(1,2,3,4,5)
    list.convert {
        it+1
    }.forEach {
        print(it)
    }
}

/**
 * 如果把返回值类型由 MutableList 更改为 Iterable
 * 那么该扩展函数 convert 就可以应用于任意类型的集合,不止再局限于 List
 */
inline fun  Iterable.convert(action:(T) -> (E)): MutableList{
    val list:MutableList = mutableListOf()
    /**
     * for循环,向list中添加数据
     * 每次添加的内容为:action(item)的结果
     * in this 的这个this,是当前对象,也就是谁调用了convert
     * this 指的就是谁
     * 所以action(item)这里的item,就是当前对象的元素
     * for循环也就是在遍历当前对象
     * 所以这里的item就是上述show方法例子中的:
     *          1,2,3,4,5,
     * 那么将1,2,3,4,5传入到action中
     * 所以在show中,convert中的it就是 1,2,3,4,5,
     * 执行完加1后返回,结果就是2,3,4,5,6
     *
     * 关于 T 和 E
     * action:   表示要接受的是一个函数
     * 函数的参数类型为 T
     * 返回值类型为 E
     * 实际上就是可以接受任意类型的参数,也可以返回任意类型的返回值
     * 在show示例中,{ it+1 } 中的 it,就是匿名函数的参数,对应类型为 T
     * it+1 就是匿名函数的返回值,对应类型为 E
     */
    for (item:T in this) list.add(action(item))
    return list
}

你可能感兴趣的:(Kotlin)