Return Tuple With Type Identifier And Data Using Sealed Classes (Kotlin)

April 13, 2018

Use Kotlin Sealed Classes to represent object of different data type.

sealed class MyData
data class StringData(val value: String): MyData()
data class IntData(val value: Int): MyData()

Return different data type depending on conditions.

fun test(isNumber: Boolean):  MyData {
    if (isNumber) {
      return MyData(1)

    return MyData("Hello")

Identify what type of data type is returned.

val data = test(true)
val output = when (data) {
  is StringData -> "I am String: ${data.value}"
  is IntData -> "I am Integer: ${data.value}"
  else -> "Unknwon"
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.