美文网首页
kotlin学习随笔之foldRight

kotlin学习随笔之foldRight

作者: 全汪汪 | 来源:发表于2017-07-28 14:49 被阅读0次

foldRight函数用途:为List接口的扩展元素,用一个自定义初始值的累计器,用累计器作用从右到左遍历数列并使用计器

源码:


public inline fun List.foldRight(initial:R,operation: (T,acc:R) ->R):R{

var accumulator = initial

if(!isEmpty()) {

val iterator = listIterator(size)

while(iterator.hasPrevious()) {

accumulator = operation(iterator.previous(),accumulator)

}

}

return accumulator

}


其实就是自己定义了一个有初始值的累计器,从右到左作用全部元素:

data classPlanets(valname: String, valdistance: Long)

val planets =listOf(Planets("a",100),Planets("b",500))

valreversePlaneName = planets.foldRight(StringBuilder()){

planet,bulider->bulider.append(planet.name)

}

println(reversePlaneName)

结果:ba

相关文章

网友评论

      本文标题:kotlin学习随笔之foldRight

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