Back to Guides
March 3, 20264 min read

Why Android Developers Love Kotlin Data Classes

Gone are the days of dense Java POJOs filled with getters, setters, and `equals()` overrides. Here is how Kotlin Data classes revolutionized JSON parsing on Android.

The Java POJO Nightmare

To model a simple API response in Java, Android developers traditionally had to write (or generate) massive classes. A simple user object with three properties could easily balloon into 50 lines of boilerplate code to handle encapsulation, hashing, and string representation.

The Kotlin Solution

Kotlin introduced the data class keyword, specifically designed to hold data. The compiler automatically derives equals(), hashCode(), toString(), and copy() from all properties declared in the primary constructor.

data class User(
    val id: Int,
    val username: String,
    val isActive: Boolean
)

Annotations and Serialization

When connecting to a backend API using Retrofit, the JSON payloads rarely use the camelCase naming convention preferred in Kotlin. Depending on the serialization library you choose (Gson, Moshi, or Kotlinx Serialization), you use annotations to bridge the gap.

Using Gson (@SerializedName)

Gson is Google's classic library. It maps JSON keys to Kotlin properties using the @SerializedName annotation.

data class User(
    @SerializedName("id")
    val id: Int,
    @SerializedName("first_name")
    val firstName: String
)

Using Moshi (@Json)

Moshi is Square's modern alternative to Gson, heavily optimized for Kotlin.

@JsonClass(generateAdapter = true)
data class User(
    @Json(name = "id")
    val id: Int,
    @Json(name = "first_name")
    val firstName: String
)

Handling Nullability

The greatest strength of Kotlin is its built-in null-safety. If an API might omit a field, you must declare it as nullable with a ?. If you don't, and the API drops the field, libraries like Moshi will immediately throw an exception, protecting your app from NullPointerExceptions deep down the stack.

Furthermore, you can easily provide default values within the data class constructor:

data class Settings(
    val themeColor: String = "#FFFFFF",
    val notificationsEnabled: Boolean = true
)