kotlin-cast

Introduction: A polyfill for Kotlin cast()
More: Author   ReportBugs   OfficialWebsite   
Tags:
blacktatty-multi-

Maven Central

kotlin-cast is a polyfill) for 3 functions that help you cast your Kotlin instances without going back in your typing flow:

inline fun <reified T : Any> Any?.safeAs(): T? = this as? T
inline fun <reified T : Any> Any?.cast(): T = this as T
inline fun <reified T : Any> Any?.assertedCast(message: () -> String): T = this as? T ?: throw AssertionError(message())

Import in your project:

[libraries]
cast = "net.mbonnin.cast:cast:0.0.1"

Usage:

val data: Any? = jsonToKotlin("{\"key\": \"value\"}")

val value = data.cast<Map<String, Any?>>()
  .get("key")
  .cast<String>() // YAYYYYY!!!

assertEquals("value", value)

Using type inference makes it even shorter:

fun doStuff(foo: Foo) { ... }

val any: Any = TODO()

doStuff(any.cast()) // cast to Foo automatically

Those functions are part of the kotlin-stdlib but not public, mainly because they break some diagnostics:

val a = "Hello"
val b: Int = a as Int // IJ will tell you "this cast can never succeed"
val c: Int = a.cast<Int>() // You'll get a crash without a warning.

Learn more in KT-8584.

Apps
About Me
GitHub: Trinea
Facebook: Dev Tools