Support for Top-Level Delegation

I have a ThreadLocal<T> and some top-level functions that delegate to functions on the associated object for the current thread. My interface for my object keeps growing causing me to practically duplicate my functions: once for the interface/class and once for the top-level current-thread-binding functions. That’s when I had a possibly insane idea: Kotlin support for Top-Level Delegation.



interface Base {
  fun print()

class BaseImpl(val x: Int) : Base {
  override fun print() { print(x) }


package com.example.derived : Base by threadLocal.get()

class Derived(b: Base) : Base by b

val threadLocal = ThreadLocal.withInitial { Derived(BaseImpl(10)) }


import com.example.derived.print

fun main() {
  print() // prints 10

Perhaps different syntax would be more appropriate. e.g. Something like companion objects but for packages.

Are there any languages that support anything like this? Is this something appropriate or even feasible for Kotlin?

This looks rather risky, especially noting that there’s an arbitrary expression in a import directive