kotlin-dynamic-delegation
Kotlin compiler plugin that allows class delegation to be dynamic like property delegations.
Features
Dynamic Delegations
The plugin provides:
public fun <R> dynamicDelegation(value: () -> R): R =
throw NotImplementedError("Implemented as intrinsic")
This function is implemented by the compiler. Here is an example.
Suppose this is your existing code and is published to the public:
interface CommandManager {
val commands: List<Command>
fun register(command: Command)
companion object : CommandManager {
}
}
Suppose then you realized the CommandManager instance should not be static (statically initialized or singleton).
You changed the CommandManager to this because you cannot remove code that have been published to the public:
interface CommandManager {
val commands: List<Command>
: CommandManager {
instance lazy { CommandManagerImpl() }
commands: List<Command> () = instance.commands
: = instance.register(command)
}
}
Now with Kotlin Dynamic Delegation, you can do instead:
interface CommandManager {
val commands: List<Command>
fun register(command: Command)
companion object : CommandManager by (dynamicDelegation(Companion::instance)) {
private val instance by lazy { CommandManagerImpl() }
}
}
Alternatively, it's also possible to do this:
Using Lazy In Functions
Functions can also be 'lazy' by making a value lazy and persistent.
override fun toString(): String = persistent { this.joinToString() }
is the same as
private val toStringTemp by lazy { this.joinToString() }
override fun toString(): String = toStringTemp
Using the plugin
build.gradle.kts
plugins {
id("me.him188.kotlin-dynamic-delegation") version "VERSION"
}
You also need to add a 'compileOnly' dependency 'me.him188:kotlin-dynamic-delegation-runtime':
For JVM projects:
dependencies {
implementation("me.him188:kotlin-dynamic-delegation:VERSION")
}
For MPP, adding to commonMain would automatically add for all targets:
kotlin.sourceSets {
commonMain {
dependencies {
implementation("me.him188:kotlin-dynamic-delegation:VERSION")
}
}
}
See VERSION from releases
Installing IntelliJ IDEA plugin
IDEA plugin can help to edit code and to report errors before compiling the code. By seeing the type cast hint(see
picture below), you will know, without compiling, that your code with dynamic delegations will work.
Plugin Marketplace Page: https://plugins.jetbrains.com/plugin/18219-kotlin-dynamic-delegation
