kotlinfunctional-programming

How to use reduce function correctly with functional programming in kotlin


I am trying to pass a function and want to use reduce on it. This is the data class

data class TestClass(
   var variable1: BigDecimal?,
   var variable2: BigDecimal?
)

This is the function which I want to work

fun aggregateAll() {
   helperfunc(TestClass::variable1::get,someDummmyFilledListOfTestClass)
}

fun helperfunc(function: () ->BigDecimal, testList:List<TestClass>) {
     var aggregatedValue:BigDecimal = BigDecimal.ZERO
     testList.map{function}.reduce{aggregatedValue,element -> aggregatedValue.add(element)}
}

Solution

  • fun main() {
        val someDummmyFilledListOfTestClass = listOf<TestClass>(
            TestClass(1.toBigDecimal()),
            TestClass(199.toBigDecimal()),
            TestClass(null),
            TestClass(501.toBigDecimal())
        )
        val result = helperfunc(someDummmyFilledListOfTestClass, TestClass::variable1::get)
                                                                     // trailing lambda
        // or val result = helperfunc(someDummmyFilledListOfTestClass) { it.variable1 }
        println(result)
    }
                                             /* lambda last parameter for trailing lambda */
    fun helperfunc(testList: List<TestClass>, function: (TestClass) -> BigDecimal?): BigDecimal {
        return testList
            // map TestClass to BigDecimal? and filter nulls
            .mapNotNull(function)
            // fold with initial value, reduce will throw exception if list is empty
            .fold(BigDecimal.ZERO) { acc, element -> acc.add(element) }
    }
    
    data class TestClass(
        var variable1: BigDecimal?
    //  var variable2: BigDecimal?
    )