Last active
November 25, 2019 15:58
-
-
Save gaerfield/b5154af312914dec187a9fc5ecfd1319 to your computer and use it in GitHub Desktop.
Just a fun way to do casts in 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
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