gpt4 book ai didi

kotlin - 如何将依赖项注入(inject) Kotlin 中的接口(interface)委托(delegate)?

转载 作者:行者123 更新时间:2023-12-01 23:44:06 24 4
gpt4 key购买 nike

我正在尝试找出如何将依赖项注入(inject) Kotlin 中的接口(interface)委托(delegate)。我有一个类:

class MyThingie {}

我想向此类添加一个字段 created_time,该字段也可能被添加到其他类。所以我可以创建一个接口(interface)和这个接口(interface)的实例实现,然后将该委托(delegate)添加到类定义中:

interface ThingieWithCreatedTS {
val created_ts: Long
}

object ThingieCreatedAtNow : ThingieWithCreatedTS {
override val created_ts: Long = System.currentTimeMillis()
}

class MyThingie : ThingieWithCreatedTS by ThingieCreatedAtNow {}

这太棒了。现在我可以在 MyThingie 的任何实例上调用 created_ts 并获取创建它的时间戳。然而,这现在很难测试。

我真的不想尝试模拟 System,我知道正确的模式是将某种 Clock 实例注入(inject)任何需要知道当前时间的对象中。这样,我可以在代码中提供一个 RealClock,在测试中我可以提供一个 FakeClock(我可以控制输出)。

目前尚不清楚如何在此模式上执行此操作。如何将实现实例传递给委托(delegate)?

最佳答案

为什么不直接使用构造函数依赖注入(inject)?

class MyThingie(
dep: ThingieWithCreatedTS = ThingieCreatedAtNow
) : ThingieWithCreatedTS by dep {}

现在您可以在测试中提供假的 ThingieWithCreatedTS 依赖

关于kotlin - 如何将依赖项注入(inject) Kotlin 中的接口(interface)委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64537623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com