Can I omit interface methods that I do not use in Kotlin?

What if I am only interested in onSeeand do not care about other events? Can I at least omit methods that do not have return values?

interface EventHandler
{
    fun onSee()
    fun onHear()
    fun onSmell()
    fun onTouch()
    fun onAwake()
    fun onSleep()
}

fun addEventHandler(handler:EventHandler)
{

}

fun Main()
{
    addEventHandler(object:EventHandler
    {
        override fun onSee()
        {
            print("I see.")
        }
    })
}
+12
source share
2 answers

Of course, you can only implement one interface method, all you have to do is provide a default implementation for the other methods in the interface declaration

interface EventHandler {
    fun onSee()
    fun onHear() { /* default implementation */ }
    fun onSmell(){ /* default implementation */ }
    fun onTouch(){ /* default implementation */ }
    fun onAwake(){ /* default implementation */ }
    fun onSleep(){ /* default implementation */ }
}

Now, when you create an instance of this interface, you only need to provide a mandatory implementation onSee(), the rest are optional

, ,

interface OnSeeEventHandler: EventHandler {
    override fun onHear() { /* default implementation */ }
    override fun onSmell(){ /* default implementation */ }
    override fun onTouch(){ /* default implementation */ }
    override fun onAwake(){ /* default implementation */ }
    override fun onSleep(){ /* default implementation */ }
}

OnSeeEventHandler onSee imeplementation

+24

, .

"" . , , null Unit, .

import java.lang.reflect.Proxy.newProxyInstance

inline fun <reified T> Any.materialize(): T = materialize(T::class.java, this)

fun <T> materialize(i: Class<T>, x: Any = object {}): T {
    @Suppress("UNCHECKED_CAST")
    return newProxyInstance(i.classLoader, arrayOf(i)) { _, m, args ->
        x.javaClass.methods
                .asSequence()
                .filter {
                    it.name == m.name
                            && it.parameterTypes!!.contentEquals(m.parameterTypes)
                }
                .map {
                    it.invoke(x, *args.orEmpty())
                }.firstOrNull()
    } as T
}

, Foo , qux():

interface Foo {
    fun bar()
    fun baz(): String
    fun qux(s: String): String
}

fun main(vararg args: String) {
    val foo = object {
        fun qux(s: String): String {
            return "Returned from qux: $s"
        }
    }.materialize<Foo>()

    println(foo.bar()) // void no-op, prints "kotlin.Unit"
    println(foo.baz()) // no-op with return value, prints "null"
    println(foo.qux("Hello")) // prints "Returned from qux: Hello"

}

  • , , .
  • (, ).
  • .
  • kotlin-reflect.
  • Kotlin, .

Kotlin, (, TypeScript Partial<T>).

, , , .

0

Source: https://habr.com/ru/post/1689489/


All Articles