Henrik Johansson
05/11/2023, 7:48 AMobject
s have all the strengths and weaknesses of a regular Java static singleton?object
that is actually a data source and I can't make it work nicely with testing where I have to inject some other than standard values.Joffrey
05/11/2023, 8:00 AMHenrik Johansson
05/11/2023, 8:03 AMYoussef Shoaib [MOD]
05/11/2023, 8:45 AMcontext
receivers as a mechanism to pass that object around. You'd simply make an interface
out of the object, use that as a context(MyInterface)
, and then at the very edge of your program you'd initialize the MyInterface
object and use it in a with
to pass it to those objectsHenrik Johansson
05/11/2023, 11:03 AMYoussef Shoaib [MOD]
05/11/2023, 11:27 AMdata class Config(val hostName: String, val port: Int)
class ConfigContext(val config: Config)
// Depending on taste, you might want to use just Config as a context, instead of a separate ConfigContext.
// It just depends on whether you want to access hostName directly, or you prefer to call config.hostName
context(ConfigContext)
fun connect() {
makeConnectionWith("${config.hostName}:${config.port}")
}
context(Config)
fun shutdown() {
shutdownServer("$hostName:$port")
}
// Usage
fun main() {
with(ConfigContext(Config(/* query system properties */))) {
connect()
if(shouldShutdown) shutdown()
}
}