기본 문법

Classes

고급 문법

컬렉션 처리

fold

// Example1
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.fold(0) { acc, num -> acc + num }
println(sum) // 15

// Example2
val dataList = listOf(
	DataModel(name = "A", value = 10),
	DataModel(name = "B", value = 20),
	DataModel(name = "A", value = 30),
)
val total = dataList.fold(mutableMapOf<String, Int>()) { acc, element ->
	val key = element.name
	val value = element.value
	acc[key] = acc.getOrDefault(key, 0) + value
	acc
}
println(total) // { "A":40, "B":20 }

associate

val dataList = listOf("one", "two", "three")

// Example1
val lengthMap = dataList.associate { it to it.length }
println(lengthMap) // { "one"=3, "two"=3, "three"=5 }

// Example2
val sameLengthMap = dataList.associateWith { it.length }
println(sameLengthMap) // { "one"=3, "two"=3, "three"=5 }

// Example3
val charMap = dataList.associateBy { it.first() }
println(charMap) // { "o"="one", "t"="three" }