Foggy day
Kotlin - extension function, fold, reduce 본문
Fold function have initial value. initial is 1 in this example. so, result of calFold is 25.
But reduce function don't have initial value. so, result of calRecude is 24, because value of List position zero is 0.
class KotlinPlayGroundActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin_play_ground)
val size = listOf(0, 3, 5, 7, 9)
println("size : ${size.length()}")
println("calFold : ${size.calFold()}")
println("calReduce : ${size.calReduce()}")
}
fun <T> List<T>.length() = this.size
fun List<Int>.calFold(): Int = this.fold(1) { a, b -> a + b }
fun List<Int>.calReduce(): Int = this.reduce { a, b -> a + b }
}
'Kotlin' 카테고리의 다른 글
Kotlin - Elvis, null check (0) | 2021.03.17 |
---|---|
Kotlin - anonymous function (0) | 2021.03.17 |
Kotlin - function, expression syntax (0) | 2021.03.16 |
Kotlin - collection about immutable, mutable (0) | 2021.03.16 |
Kotlin - Singleton (0) | 2021.03.16 |