Kotlin

Kotlin - extension function, fold, reduce

jinhan38 2021. 3. 17. 00:01

 

 

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 }

}