Type inference for return types of longer functions


#1

I've been playing with Kotlin for a bit, and so far, it's mostly been rather nice to use. It's my intention to possibly create a language plugin for OCaml (I'm still learning OCaml, so this will probably take a while) for IDEA at some point, as the current one doesn't work; and I'm considering either Scala or Kotlin for this purpose. Kotlin's reduction of verbosity from Java is excellent, and I like how class objects are implemented (coming from Ruby and Scala).

My question is if there will be type inference for functions of the form:

fun sum(a : Int, b : Int) : Int {
    // do many other things
    return something
}

be implemented? Or will we always need to specify the return type?

Also, will an explicit return statement always be needed? Or it be possible at some point have the last statement be the return value of the function?


#2

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)

#3

So I can safely say that Kotlin will not, now or in the future, be doing type inference for functions with a block body (which is my actual question, thanks for the correct phrasing)?

What about having the last expression in the block being the return value (similar to what Ruby, Scala, and some other languages do)?


#4

Correct. We beleive that for block body functions "return" should be explicit so reader of the code is able to find function exit-point at a glance.