Kotlin / dukat

Converter of <any kind of declarations> to Kotlin external declarations
557 stars 42 forks source link

Union type could be represented with inline fun and contract #396

Open KotlinIsland opened 4 years ago

KotlinIsland commented 4 years ago
declare function foo(): string | number

It's pretty messy, but this could be represented with:

external fun foo(): FooResult /* String | Number */

external interface FooResult

@ExperimentalContracts
@Suppress("INCOMPATIBLE_TYPES")
inline fun FooResult.isString(): Boolean {
    contract { returns(true) implies(this@isString is String) }
    return this.asDynamic() is String
}
@ExperimentalContracts
@Suppress("INCOMPATIBLE_TYPES")
inline fun FooResult.isNumber(): Boolean {
    contract { returns(true) implies(this@isNumber is Number) }
    return this.asDynamic() is Number
}

@ExperimentalContracts
fun main() {
    val f = foo()
    when {
        f.isString() -> f.length
        f.isNumber() -> f.toInt() + 1
    }
}