kotlin学习随笔之foldRight

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)