Hello. I’m developing Android app and sometimes hard to avoid Fat Activity(aka God Activity).
interface Interface1 {
fun f11()
fun f12()
fun f13()
}
class FatActivity: Activity, Interface1 {
override fun f11() {}
override fun f12() {}
override fun f13() {}
}
What’s worse, if I want to refactor, I can’t ab-test between old one and new one
because Activity is written in Manifest with scheme.
So I decided to delegate implementation.
interface Delegate {
fun getDelegate(): Interface1
}
class SlimActivity: Activity, Delegate {
private lateinit var delegation: Interface1
override fun getDelegate() = delegation
}
Code became slimmer and ready to ab-test the implementation.
but I got frustrated by runtime-typecheck api.
fun useInterface1(o: Activity) { // api signature fixed
(o as? Interface1)?.f11()
}
I googled and finally found the solution with reified.
inline fun <reified T : Any> getIntf(o: Any): T? {
if (o is T) {
return o
} else if (o is Delegate) {
val d = o.getDelegate()
if (d is T) // I wanted to call getIntf recursively but inline doesn't support recursive.
return d
}
return null
}
fun useInterface1(o: Activity) { // api signature fixed
getIntf<Interface1>(o)?.f11()
}
What I suppose is the generalized version of this getIntf.
maybe with fancy syntax like… as, by … I don’t know…
Kotlin is a delegation-friendly language and this can make it more.