kotlin - 如何在 Kotlin 中使用 foldRight()?

标签 kotlin

我试试这个代码

        println(listOf(1, 2, 4).foldRight(0) { total, next ->
            total - next
        })

我认为它的工作原理是 0 + 4 - 2 - 1 = 1。
但它返回 3。为什么?
对不起这个愚蠢的问题。

最佳答案

foldRight 通过从右到左累加结果来工作。在你的情况下,它会做

(1 - (2 - (4 - 0))) = (1 - (2 - 4)) = 1 - (-2) = 3

请注意,您的操作的参数顺序错误,foldRight 会将下一个元素作为第一个参数传递给您,将累加器作为第二个参数传递给您。见 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold-right.html .如果你交换它们,你就会有

(((0 - 4) - 2) - 1) = - 7

除非我出了什么问题

关于kotlin - 如何在 Kotlin 中使用 foldRight()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47013801/

相关文章:

android - 在 Kotlin 中使用 Flowable 的多个 retrofit2 请求

java - 记录整个HttpRequest的最佳方法

kotlin - 在 Kotlin 中声明 Byte 会出现编译时错误 'The integer literal does not conform to the expected type Byte'

android - 在 Android 中使用 Kotlin 在 RecyclerViewAdapter 中实现自定义接口(interface)

kotlin - kotlin的运算符重载中plus和plusAssign有什么区别?

android - Jetpack Compose 带按钮的倾斜行

gradle - 如何在多个 Gradle 项目之间共享样板 Kotlin 配置?

command-line - 从命令行使用 jar 依赖项编译 Kotlin

Kotlin 编码约定 : Horizontal whitespace

android - 为什么我们应该在 Android 的 MVP 模式中使用界面?