Extensions function to implement interface

Apples new Language Swift looks a lot like Kotlin and has a feature that would be really useful in Kotlin: The ability to extend a class to support an interface by adding extension methods.  The syntax for this could be (taken strait from Swift)

trait Transformable {   fun <T> transformTo(type: Class<T>):T }

extension String: Transformable {   override fun <T> transformTo(type: Class<T>): T{   when(type) {   javaClass<Boolean>() -> this.startsWith("T");   ...

  }
  }
}

16 Likes

Yes, it's a nice feature, not very straightforward to implement on the JVM though: it requires either dynamic method resolution (invokedynamic might help, but then we'd need to limit the scope of calls that are bound by invokedynamic, so it can't be uniform), or wrapping (this plainly breaks identity and equality).

6 Likes

hope we will have this feature some day

6 Likes

I post here because I’ve found this on google but this did not give me the answer I was looking for …

With kotlin you can directly do something like this :

fun String.asTransformable() = object:Transformable {
  override fun <T> transformTo(type: Class<T>): T = with(this@asTransformable) {
    when (type) { ... }
  }
}

the key here is the anonymous implementation and the with(this@asTransformable) which allows to get access to the instance nearly as normally as you could expect

4 Likes

But you can’t do something like this:

suspend fun <T> ListenableFuture<T>.suspendDisposable(): T where T : Disposable =
    suspendCancellableCoroutine {
        it.invokeOnCancellation {
            if (!isDone) {
                cancel(true)
                return@invokeOnCancellation
            }
            val result = get()
            result.dispose()
        }
        addListener(
            {
                it.resume(get())
            },
            BlockingExecutor
        )
    }