Return different type of data with Seald Class in Kotlin

This article describe a solution to return different type of data in one function with Sealed class.


In one API, it will return different type of data, and the fields of the data is totally different, for example, the response data is like this:type: <data type><data json>----
type: data1{key11: "value 11", key12: "value 12"}----
type: data2{key21: "value 21", key22: "value 22", key23: "value 23"}

When I get the response content, I will parse the first line and get the data type, and then parse the data json according the data type.

Solution with Sealed Class

Define the response like below:sealed class Response {
   data class FirstResponse(val key11: String, val key12: String) : Response()
   data class SecondResponse(val key21: String, val key22: String, val key23: String) : Response()

Example of use the Response , this example just create the class directly, the classes might create from json by getResponses(): List<Response> {
   val result = mutableListOf<Response>()
   result.add(Response.FirstResponse(key11 = "value 11", key12 = "value 12"))
   result.add(Response.SecondResponse(key21 = "value 21", key22 = "value 22", key23 = "value 23"))
   return result

fun main() {
   val list = getResponses()
   for (item in list) {
       when (item) {
           is Response.FirstResponse -> {
               println("The value is first response, key11: ${item.key11}, key12: ${item.key12}")
           is Response.SecondResponse -> {
               println("The value is second response, key21: ${item.key21}, key22: ${item.key22}, key23: ${item.key23}")