Kotlin Fold Example

This Kotlin tutorial shows you example that uses Fold method on List, Map of Objects.

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

1. fold()

We will get total quantity for of Product(name,quantity) List/Map using fold() method:

inline fun  Iterable.fold(initial: R, operation: (acc: R, T) -> R): R {
    var accumulator = initial
    for (element in this) accumulator = operation(accumulator, element)
    return accumulator
}

This function helps to accumulate value starting with initial value, then apply operation from left to right to current accumulator value and each element.

2. foldRight()

If you want to apply operation from right to left, you can use foldRight():

inline fun  List.foldRight(initial: R, operation: (T, acc: R) -> R): R {
    var accumulator = initial
    if (!isEmpty()) {
        val iterator = listIterator(size)
        while (iterator.hasPrevious()) {
            accumulator = operation(iterator.previous(), accumulator)
        }
    }
    return accumulator
}

III. Practice

0. Product Class
package com.javasampleapproach.fold

data class Product(val name: String, val quantity: Int) {
}
1. List
package com.javasampleapproach.fold

fun main(args: Array) {

	val total = listOf(1, 2, 3, 4, 5).fold(0, { total, next -> total + next })
	println("total: " + total)

	val mul = listOf(1, 2, 3, 4, 5).fold(1, { mul, next -> mul * next })
	println("mul: " + mul)

	val productList = listOf(
			Product("A", 100),
			Product("B", 200),
			Product("C", 300),
			Product("D", 400),
			Product("E", 500)
	)

	val quantity = productList.map { it.quantity }.fold(0, { total, next -> total + next })
	println("quantity: " + quantity)
}

Result:

total: 15
mul: 120
quantity: 1500
2. Map
package com.javasampleapproach.fold

fun main(args: Array) {

	val productMap = mapOf(
			"a" to Product("A", 100),
			"b" to Product("B", 200),
			"c" to Product("C", 300),
			"d" to Product("C", 400),
			"e" to Product("C", 500)
	)

	val quantity = productMap.map { it.value.quantity }.fold(0, { total, next -> total + next })
	println("quantity: " + quantity)
}

Result:

quantity: 1500


By grokonez | August 29, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*