Relating to previous example, as for how general Kotlin union types could be implemented from technical point of view, especially for types from another modules we don’t control, a compiler could emit synthetic sealed
classes for each union type. More less like this:
fun fetchJsonObject(): JSONObject | FetchJsonError {
return when {
no internet -> FetchJsonError.NoInternet
timeout -> FetchJsonError.Timeout
bad json -> FetchJsonError.BadJson
else -> jsonObject
}
}
could be compiled to this:
@JvmSynthetic
sealed class fetchJsonObject$union {
data class JSONObject$unionType(val value: JSONObject): fetchJsonObject$union
data class FetchJsonError$unionType(val value: FetchJsonError): fetchJsonObject$union
}
fun fetchJsonObject(): fetchJsonObject$union {
return when {
no internet -> FetchJsonError$unionType(FetchJsonError.NoInternet)
timeout -> FetchJsonError$unionType(FetchJsonError.Timeout)
bad json -> FetchJsonError$unionType(FetchJsonError.BadJson)
else -> JSONObject$unionType(jsonObject)
}
}
So, it’s pretty doable in my opinion.