I have an existing class with an instance method buildHierarchyUncached whose signature can be found below.
private fun buildHierarchyUncached(date: LocalDate): Node { ... }
I would like to provide a public function buildHiearchy, which is a memoized version of buildHierarchyUncached. I can get closer to what I want:
val buildHiearchy = Memoize<LocalDate, Node>({buildHierarchy(it)})
Which can be called as:
hierarchyService.buildHiearchy(businessDate)
Using:
class Memoize<I, O>(val func: (I) -> O): (I) -> O{ val cache = hashMapOf<I, O>(); override fun invoke(p1: I): O { return cache.getOrPut(p1, { func(p1) } ) } }
I would like to be able to declare a memoized function as a function instead of a property that is not a huge deal, although I believe that it helps readability. Like this:
fun buildHierarchy(date: LocalDate): Node = Memoize<LocalDate, Node>({ buildHierarchyUncached(it)})
but this does not compile: "Type mismatch. Required Node. Memoize found."
Also, why is this not compiling?
val buildHiearchy = Memoize<LocalDate, Node>({(date) -> buildHierarchy(date)})
source share