skip icon indicating copy to clipboard operation
skip copied to clipboard

One-line function call on optional value yields Kotlin compile error: Type mismatch: inferred type is Unit? but Unit was expected

Open marcprux opened this issue 2 years ago • 0 comments

If a Void function has a single-line that invokes another Void function, we transpile it into a single line like: fun x(): Unit = f(), but that raises a compile error because f() returns Unit?.

For example, the Swift:

class Thing {
    var t: Thing? = nil

    init() {
    }

    func go() {
    }

    func optionalCall() {
        t?.go()
    }
}

transpiles into the Kotlin:

internal open class Thing {
    internal open var t: Thing? = null

    internal constructor() {
    }

    internal open fun go() = Unit

    internal open fun optionalCall(): Unit = t?.go()
}

which yields the compile error:

Type mismatch: inferred type is Unit? but Unit was expected

The only workaround is to add another line to the function, like:

    func optionalCall() {
        let x = t?.go()
        _ = x
    }

marcprux avatar Nov 27 '23 14:11 marcprux