美文网首页
Kotlin学习-常用高阶函数

Kotlin学习-常用高阶函数

作者: A_si | 来源:发表于2017-11-08 23:25 被阅读338次
    • map->一个集合改变元素后生成另外一个集合

    比如一张工资表,每人工资补贴10块高温费。Java写法遍历然后添加,而Kotlin简洁多了:

     val form = listOf(1,2,3,4,5)
    
       val newForm =  form.map { it+10 }
    

    map函数的签名是变换T类型返回一个R类型集合:

    public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
        return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
    }
    
    public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C {
        for (item in this)
            destination.add(transform(item))
        return destination
    }
    
    

    首先看mapto函数签名,第一个参数是C-目标集合,然后是一个表达式将T类型的transform变换成R类型,函数的返回值是C。函数里是遍历原始集合,然后遍历的元素通过transform表达式变换,添加到目标集合C中。
    而map函数的签名就是传入一个表达式,对表达式不太懂的可能看不明白。其分解如下:

        form.map ({ it ->  it+10 }) //{ it ->  it+10 }就是transform: (T) -> R
        form.map ({ transform: Int ->  transform+10 }) //这样应该明白了吧
    

    map函数retrun 的mapto函数,第一个参数就是一个新的集合实例,第二个就是这个表达式,如果还不懂,将这个表达式写成普通函数params:

    fun   params(  transform: Int      ): Int{
        return transform+10
    }
    
    public inline fun <T, R> Iterable<T>.map( params(transform:Int) ): List<R> {
        return mapTo(ArrayList<R>(collectionSizeOrDefault(10)),params(transform:Int))
    }
    
    public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C,params(transform:Int)): C {
        for (item in this)
            destination.add(params(item))
        return destination
    }
    
    

    然后在map这里调用这个params函数,传给mapto。mapto里面,遍历的时候,把item传给这个params函数。

    • reduce->求和,阶乘

    上面工资表添加完了高温补贴,然后要算下一共支出多少,Java是遍历相加,Kotlin当然要智能了:

        newForm.reduce { acc, i -> acc+i }
    

    看下reduce的实现:

    public inline fun <S, T: S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S {
        val iterator = this.iterator()
        if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
        var accumulator: S = iterator.next()
        while (iterator.hasNext()) {
            accumulator = operation(accumulator, iterator.next())
        }
        return accumulator
    }
    

    acc第一次是集合的第一个元素。i是第二个元素。然后operation表达式传入acc和i。然后acc等于这个operation表达式的返回值。继续循环。。。
    那阶乘怎么写呢?

        val  mulList = listOf(1,2,3,4)
        val mul = mulList.reduce { acc, i -> acc * i }
    
        print(mul)
    

    acc第一次等于1,i等于2.然后acc * i = 1 * 2=2,这个结果赋值给acc。acc=2.然后i=3,acc * i=2 * 3=6,然后赋值给acc=6.然后i=4,acc * i=6*4=24.

    • fold-添加初始值,变换类型

    公司除了发工资,还要支出100的房租。所以:

        val  money = listOf(1,2,3)
        val sb= StringBuilder("$")
        val fold = money.fold(sb) { acc, i -> acc.append(i) }
    

    fold第一个参数是acc初始值。i是集合第一个元素。

    • joinToString-使用分隔符使集合所有元素分离,可以使用给定的(前缀)和(后缀)
        val  money = listOf(1,2,3)
    
       print(money.joinToString("=="))
       print( money.joinToString { "== $it" })
    
    • filter-过滤符合条件的元素
        val  money = listOf(1,2,3)
    
        money.filter { it==2 }.forEach(::print) //2
    
    • takeWhile-从第一个元素开始过滤,遇到不符合条件的元素即退出。
        val  money = listOf(1,2,3,4,5,6)
    
        money.takeWhile { it<5 }.forEach(::print)
    

    相关文章

      网友评论

          本文标题:Kotlin学习-常用高阶函数

          本文链接:https://www.haomeiwen.com/subject/cepumxtx.html