memoize

fun <R> () -> R.memoize(): () -> R(source)

Memoizes the given pure function so that invocations with the same arguments will only execute the function once.

import arrow.core.memoize
fun someWorkIntensiveFunction(someParam: Int): String = "$someParam"

fun main() {
//sampleStart
val memoizedF = ::someWorkIntensiveFunction.memoize()

// The first invocation will store the argument and result in a cache inside the `memoizedF` reference.
val value1 = memoizedF(42)
// This second invocation won't really call the `someWorkIntensiveFunction` function
//but retrieve the result from the previous invocation instead.
val value2 = memoizedF(42)

//sampleEnd
println("$value1 $value2")
}

Note that calling this function with the same parameters in parallel might cause the function to be executed twice.


fun <P1, R> (P1) -> R.memoize(): (P1) -> R(source)
fun <P1, P2, R> (P1, P2) -> R.memoize(): (P1, P2) -> R(source)
fun <P1, P2, P3, R> (P1, P2, P3) -> R.memoize(): (P1, P2, P3) -> R(source)
fun <P1, P2, P3, P4, R> (P1, P2, P3, P4) -> R.memoize(): (P1, P2, P3, P4) -> R(source)
fun <P1, P2, P3, P4, P5, R> (P1, P2, P3, P4, P5) -> R.memoize(): (P1, P2, P3, P4, P5) -> R(source)

See also