Kotlin减少2d列表的功能不起作用

OMG*_*POP 2 android kotlin

我需要得到一个2d列表的总大小.这是我的实施:

    fun totalSize(parts: List<List<String>>): Int {
        return parts.reduce { total, next -> total + next.size }
    }
Run Code Online (Sandbox Code Playgroud)

我得到类型推断失败.必需的Int,Got List.但是next.size应该返回Int.

Aja*_*les 5

更好:总和期间的地图操作(来自@Ruckus T-Boom评论)

parts.sumBy { it.size }
Run Code Online (Sandbox Code Playgroud)

原文:首先将内部列表映射到它们的大小(猜测Kotlin语法):

parts.map { l -> l.size }.reduce { total, i -> total + i }
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用`parts.map {it.size} .sum()`代替. (2认同)
  • 甚至只是`parts.sumBy {it.size}` (2认同)