Skip to content

Instantly share code, notes, and snippets.

@vyo
Last active February 2, 2018 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyo/d0a8ecfc405cea2bcc7878824e059809 to your computer and use it in GitHub Desktop.
Save vyo/d0a8ecfc405cea2bcc7878824e059809 to your computer and use it in GitHub Desktop.
Kotlin type inference greatness
/**
* this little piece of magic provides some nice type inference info to the compiler
*
* courtesy of [StackOverflow](http://stackoverflow.com/a/33420043)
*/
inline fun <reified T> fromJSON(json: String): T = gson.fromJson<T>(json, object : TypeToken<T>() {}.type)
//usable as follows, and type inference doesn't even break a sweat
val project: Project = fromJSON(request.body())
val client = fromJSON<Client>(request.body())
/**
* using Moshi instead of Gson
*/
inline fun <reified T> fromJSONMoshi(json: String): T = moshi.adapter<T>(object : TypeToken<T>() {}.type).fromJson(json)!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment