I have an existing class with an instance method buildHierarchyUncached whose signature can be found below.

private fun buildHierarchyUncached(date: LocalDate): Node { ... }

我想提供一个function的公共buildHiearchy,它是buildHierarchyUncached的记忆版本.我可以接近我想要的:

val buildHiearchy = Memoize<LocalDate, Node>({buildHierarchy(it)})

Which can be called like:

hierarchyService.buildHiearchy(businessDate)

使用:

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 the memoized function as a function instead of a property, which is not a huge deal, though I think it helps readability. Like this:

fun buildHierarchy(date: LocalDate): Node = Memoize<LocalDate, Node>({ buildHierarchyUncached(it)})

但这没有编译:"类型不匹配.必需的 node .找到Memoize."

还有,为什么不编译?

val buildHiearchy = Memoize<LocalDate, Node>({(date) -> buildHierarchy(date)})

推荐答案

By the nature of the problem, you need a class field to store your cache (the cached value or a caching object or a delegate). So you have to declare a val in the class somewhere, since functions can't do that.

请注意,当您声明buildHiearchy值时,一件事中有两件事:在类字段中存储Memoize<..>(..)对象,然后得到invoke()函数(在其他地方声明,但仍然..).我知道没有其他语法就无法声明函数并获取字段存储.

代码段使用过时的语法.如下所示(无括号):

val buildHiearchy = Memoize<LocalDate, Node>({date -> buildHierarchy(date)})

Kotlin相关问答推荐

等待下一个值时暂停Kotlin Coroutine

带有Spring Boot和Kotline的可嵌入实体

&x是T&q;和&q;(x为?T)!=空(&Q;)?

捕捉异常是Kotlin协程中的反模式吗?

在 Kotlin 中定义基于多态函数的泛型函数

如何访问嵌套在另一个 map 中的 map 中的值(在 kotlin 中)

使用 StateFlow 时如何移除监听器?

区分函数和扩展

如果带注释的成员未被特定块包围,则发出 IDE 警告

如何将jooq multiset的结果映射到Hashmap(Java Map)?

kotlin 单例异常是好是坏?

这是什么 Kotlin 类型:(String..String?)

类型不匹配:Required: Context, Found: Intent

Kotlin 使用迭代索引过滤 lambda 数组

如何为 material.Slider 视图创建绑定适配器?

Kotlin - 当表达式返回函数类型

什么是 .kotlin_builtins 文件,我可以从我的 uberjars 中省略它们吗?

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

类型推断失败:RecyclerViewActions.scrollTo()