https://kotlinlang.org logo
#announcements
Title
# announcements
m

Matt Thiffault

10/10/2019, 12:45 AM
I'm guessing no, but is it possible to do something cool like make an type implement an interface via extension functions? Eg. can I add a .close() extension to something and then pass it as AutoCloseable?
n

nwh

10/10/2019, 12:51 AM
There was a KEEP proposal for this, but I can't seem to find it, unfortunately. Hopefully someone else know where it's ended up
s

streetsofboston

10/10/2019, 1:05 AM
m

Matt Thiffault

10/10/2019, 1:06 AM
Haha, nice. I'm amused that it's Raul's proposal since it's Arrow that I'm interacting with.
n

nwh

10/10/2019, 1:10 AM
I feel like that proposal got a bit wild. I started seeing the
with
keyword in arguments and stuff and found myself very lost
n

nfrankel

10/10/2019, 5:36 AM
actually, it’s quite easy without it i had a class called
JetInstance
which has a
shutdown
method and wanted to use
use()
on it to automatically
close()
it with delegate and extension method, this is a breeze:
Copy code
class CloseableJet(private val instance: JetInstance) : Closeable, JetInstance by instance {
    override fun close() {
        shutdown()
    }
}

fun JetInstance.withCloseable() = CloseableJet(this)
now:
Copy code
Jet.newJetClient().withCloseable().use {
    it.newJob(pipeline(), config)
}
👏 1
m

Matt Thiffault

10/10/2019, 6:06 PM
Ok that "by instance" trick is awesome and I didn't know it exits, thank you!
s

streetsofboston

10/10/2019, 6:07 PM
Yup, Kotlin’s way of doing some mix-ins and traits 🙂
2 Views