Paul Woitaschek
05/08/2017, 9:22 AMlovis
05/08/2017, 9:26 AMPaul Woitaschek
05/08/2017, 9:27 AMlovis
05/08/2017, 9:29 AMPaul Woitaschek
05/08/2017, 9:30 AMlovis
05/08/2017, 9:35 AMfun <T,R: Bundler> T.fromBundle(b: Bundle) : R {
return UnBundler().fromBundle(b) //will throw if not possible
}
val thing: Thing = fromBundle(extras)
reified
thoughabstract class UnBundler(val canHandle: KClass<*>) {
companion object {
val unbundlers: MutableList<UnBundler> = arrayListOf()
inline fun <reified R> unBundle(b: Bundle): R {
val unbundler = unbundlers.find { it.canHandleClass(R::class) }
if (unbundler == null)
throw UnBundlerNotRegistered()
return unbundler.unbundle(b) as R
}
}
fun canHandleClass(kClass: KClass<*>): Boolean {
return kClass == canHandle
}
abstract fun unbundle(b: Bundle): Any
}
...
inline fun <reified R: Bundler> Any.fromBundle(b: Bundle) : R {
return UnBundler.unBundle<R>(b)
}
Of course, just as you said, you have to manage two classes. Register a new UnBundler
for each new class that implements Bundler