Last active
February 2, 2018 15:40
-
-
Save vyo/d0a8ecfc405cea2bcc7878824e059809 to your computer and use it in GitHub Desktop.
Kotlin type inference greatness
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
/** | |
* 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