Using Kotlin Data Classes for CustomTypeMappings in Apollo & Android

A neat trick for working with incoming/outgoing data for GraphQL queries

mvndy

--

For those that haven’t heard yet, GraphQL is a hot new query language for your API. The setup between ourselves and the API team had several bumps and wild cards, but we really had a great time exploring a new framework responsible for creating a GraphQL client with Android. While it took us a while to really get going, I found that working with GraphQL on Android really feels a lot more modern and a lot less clunky in comparison to the complex network layer usually required for CRUD APIs.

While this post will not discuss the intricacies of GraphQL or cover the basics of getting Android set up as a consumer client with Apollo, this short blurb covers a really neat method Ryan Casler came up taking advantage of Kotlin data classes with Apollo’s CustomTypeMapping feature.

Apollo supports custom scalar types by allowing you to define mappings in your build.gradle file. This will tell the code generator/gradle plugin what type to use when generating the class.

apollo {
generateKotlinModels = true
customTypeMapping = [
"AccountUserId" : "kotlin.String",
]
}

In other words, we’re telling Apollo to work with kotlin.String when we come across a AccountUserId type in GraphQL. Likewise, you can map Kotlin data classes to to GraphQL types, which can be really helpful for things like reformatting incoming GraphQL data in such a way that better integrated for your existing Android code.

It’s important to note that customTypeMappings is for more than just Query calls— the custom type adapter is for all kinds of GraphQL calls: you can feed in customTypeMappings for Mutations or Request bodies and you can still pass in customTypeMappings into your generated Apollo queries.

Likewise, you can map Kotlin data classes to to GraphQL types, which can be really helpful for things like reformatting incoming or outgoing GraphQL data in a way that is usable for your Android code.

Let’s say that you have a GraphQL API that queries for bank transactions, but the API team has taken the liberty of…

--

--

mvndy

software engineer and crocheting enthusiast. co-author of "Programming Android with Kotlin"