Am I right that implementing interfaces by delegation is restricted to constructor fields?
I'd quite like to delegate to a method that returns an instance of the interface, as I can in Groovy.
Rob Elliot
10/11/2022, 7:20 AM
Groovy:
Copy code
class ThreadLocalDslContext implements DSLContext {
private final ThreadLocal<DSLContext> threadLocalDslContext = new ThreadLocal<>()
private final Database database
ThreadLocalDslContext(Database database) {
this.database = database
}
@Delegate
private DSLContext getContext() {
return threadLocalDslContext.get() ?: database.dsl
}
}
Here
ThreadLocalDslContext
delegates to the result of
getContext()
. But I don't think I can convert this class to Kotlin without manually delegating all the methods on
DSLContext
to the result of
getContext()
?
Rob Elliot
10/11/2022, 7:22 AM
Kotlin - does not compile:
Copy code
class ThreadLocalDslContext(
private val database: Database,
) : DSLContext by this::getDslContext {
private val threadLocalDslContext: ThreadLocal<DSLContext?> = ThreadLocal<DSLContext?>()
fun getDslContext() = threadLocalDslContext.get() ?: database.dsl
}
Rob Elliot
10/11/2022, 7:32 AM
(It's really irritating that IntelliJ can't even do
Delegate Methods
as it would for a Java class. And it takes about 3 GB of memory and 20 seconds for it to create the stub methods with TODO as their implementation!)