티스토리 뷰

공부

[kotlin] reduce & fold

승가비 2023. 3. 10. 03:59
728x90
val numbers = emptyList<Int>()

val sumFromTen = numbers.fold(10) { total, num -> total + num }
println("folded: $sumFromTen") // folded: 10
val sum = numbers.reduce { total, num -> total + num }
println("reduced: $sum")
folded: 10

Empty collection can't be reduced.
java.lang.UnsupportedOperationException: Empty collection can't be reduced.
	at kr.leocat.test.FoldTest.test(FoldTest.kt:35)
  ...

https://blog.leocat.kr/notes/2020/03/09/kotlin-reduce-and-fold

 

[Kotlin] reduce 와 fold

Kotlin 컬렉션에는 컬랙션 내의 데이터를 모두 모으는(accumulate) 함수인 reduce()와 fold()가 있다.

blog.leocat.kr

 

728x90
댓글