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

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

sealed class MyDatadata 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"}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.