foldRight函數(shù)用途:為L(zhǎng)ist接口的擴(kuò)展元素背犯,用一個(gè)自定義初始值的累計(jì)器,用累計(jì)器作用從右到左遍歷數(shù)列并使用計(jì)器
源碼:
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
}
其實(shí)就是自己定義了一個(gè)有初始值的累計(jì)器靠娱,從右到左作用全部元素:
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)
結(jié)果:ba