Kotlin fold 高级函数 累加

fun main() {
    val numbers1 = listOf<Int>(1, 2, 3, 4);
    // i 代表元素 acc 代表0
    val res = numbers1.fold(0) { acc, i ->
        println("Accumlated value $acc")
        // 元素
        acc + (i * 3)
    }
    println(res)

//    Accumlated value 0     0+(1*3)=3
//    Accumlated value 3      3+(2*3)=9
//    Accumlated value 9     9+(3*3)=18
//    Accumlated value 18    18+(4*3)=30
    val res2 = numbers1.map { it * 3 }.sum()
    println(res2)


}

直接换成sum的话。就很清晰了。。。

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/124133672