Skip to content

Instantly share code, notes, and snippets.

@gaerfield
Last active November 25, 2019 15:58
Show Gist options
  • Save gaerfield/b5154af312914dec187a9fc5ecfd1319 to your computer and use it in GitHub Desktop.
Save gaerfield/b5154af312914dec187a9fc5ecfd1319 to your computer and use it in GitHub Desktop.
Just a fun way to do casts in kotlin
inline fun <reified T> Any.cast() =
try { val toBeCasted = this; with(jacksonObjectMapper()) { readValue<T>(writeValueAsString(toBeCasted)) } }
catch (e: Exception) { throw ClassCastException("Can't convert from [${this::class}] to [${T::class}]:\n\t${e.message}") }
data class AClass(val name: String, val age: Int)
data class BClass(val name: String, val age: Int)
@Test
fun example(){
val a = AClass("whoop", 42)
val b = a.cast<BClass>()
assertFailsWith<ClassCastException> { a as BClass }
assertNotEquals(a, b as Any)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment