Kotlin provides “semicolon inference”: syntactically, subsentences (e.g., statements, declarations etc) are separated by the pseudo-token SEMI, which stands for “
Kotlin seems to mostly infer semicolons eagerly. There seem to be exceptions (as shown in Jayson Minard's enum example).
Generally, the type system will catch badly inferred semicolons, but here are some cases where the compiler fails.
If an invocation's arguments are in the next line (including the parenthesis), Kotlin will assume that arguments are simply a new parenthesised expression statement:
fun returnFun() : (x: Int) -> Unit {
println("foo")
return { x -> println(x) }
}
fun main(args: Array) {
println("Hello, world!")
returnFun()
(1 + 2) // The returned function is not called.
}
A more common case could be the following, where we have a return with the expression in the next line. Most of the time the type system would complain that there is no return value, but if the return type is Unit
, then all bets are off:
fun voidFun() : Unit {
println("void")
}
fun foo() : Unit {
if (1 == 1) return
voidFun() // Not called.
}
fun bar() : Unit {
if (1 == 1)
return
voidFun() // Not called.
}
The bar
function could potentially happen, if the return voidFun()
wouldn't fit on one line. That said, must developers would simply write the call to the function on a separate line.