Support for Top-Level Delegation


#1

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.

e.g.

Base.kt:

interface Base {
  fun print()
}

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

Derived.kt:

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

class Derived(b: Base) : Base by b

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

Main.kt:

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?


#2

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