Type inference for return types of longer functions

If your function is really short (exactly one expression), you can use expression body syntax. In this case, return type may be omited.

fun sum(a : Int, b : Int) = a + b

fun sum(a : Int, b : Int) = if (a > b) a - b else (a + b)

Return type must be provided in two cases:

  • function is public or protected, i. e. it is part of API, and you don't want it's signature to change implicitly;
  • function has block body, and it may be hard to infer return types by compiler and human reading the code :)

If function is declared with block body, “return” is always neccessary, if it has expression body, “return” should be skipped.

Side note: for function literals (a.k.a. lambdas) it is a bit different, because they are one-time functions and syntax is needed to be really short:

  1. Parameter types are usually inferred.
  2. Body may contain several statements/expressions, the last one is considered as return value. “Return” is not necessary (if you don’t mean non-local return)
1 Like