Kotlin减少功能为2d列表不起作用
我需要得到一个2d列表的总大小。 这是我的实现:
fun totalSize(parts: List<List<String>>): Int { return parts.reduce { total, next -> total + next.size } }
我得到类型推断失败。 必需的Int,有名单。 但是next.size应该返回Int。
更好:总和期间的地图操作(来自@Ruckus T-Boom评论)
parts.sumBy { it.size }
原文:首先将内部列表映射到它们的大小(猜测Kotlin语法):
parts.map { l -> l.size }.reduce { total, i -> total + i }
在reduce
, total
的第一个值是列表的第一个元素,这也是一个列表。 所以reduce
的返回值的推断类型必须是List
。
你可以用fold
来代替:
return parts.fold(0, { total, next -> total + next.size })