Here is a composable IHandler<T>
implementation. Any ideas on how to make it shorter and get rid of exception being thrown?
interface Handler<T> {
fun handle(e: T)
operator fun <TOther> plus(other: Handler<TOther>): Handler<Any> =
Composite(this, other)
private class Composite<T1, T2>(
private val left: Handler<T1>,
private val right: Handler<T2>) : Handler<Any> {
override fun handle(e: Any) {
try { left.handle(e as T1) } catch(ex: ClassCastException) { }
try { right.handle(e as T2) } catch(ex: ClassCastException) { }
}
}
}
Smoke test looks like this:
val h = A() + B()
h.handle("33") // prints 'String: 33'
h.handle(33) // prints 'Int: 33'
where:
class A : Handler<String> {
override fun handle(e: String) = Debug.println("String", e.toString())
}
class B : Handler<Int> {
override fun handle(e: Int) = Debug.println("Int", e.toString())
}