skip
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
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
}