Created
May 8, 2017 10:19
-
-
Save lmller/9f3cd142787ca81932bf0f121a05d3c3 to your computer and use it in GitHub Desktop.
Reified generics kotlin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//me playing around for https://kotlinlang.slack.com/archives/C0922A726/p1494235351616257 | |
fun main(args: Array<String>) { | |
UnBundler.unbundlers.add(object: UnBundler(canHandle = Test::class) { | |
override fun unbundle(b: Bundle): Any { | |
println("it works!") | |
return Test() | |
} | |
}) | |
TestTest() | |
} | |
inline fun <reified R: Bundler> Any.fromBundle(b: Bundle) : R { | |
return UnBundler.unBundle<R>(b) | |
} | |
class TestTest { | |
init { | |
//val test: NotTest = fromBundle(object: Bundle{}) // throws | |
val test: Test = fromBundle(object: Bundle{}) // works | |
} | |
} | |
abstract 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 | |
} | |
interface Bundle | |
interface Bundler | |
class UnBundlerNotRegistered : Throwable() { | |
} | |
class Test: Bundler { | |
} | |
class NotTest: Bundler { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment