Anonymous Functions

What happens when the compiler is not smart enough to understand your lambda expression?

The Problem: Return Types

A lambda expression allows us to specify the types for any parameters, by adding the types in the parameter list:

  val squarifier = { x: Int -> x * x }

  println(squarifier.invoke(3))

Here, we specifically declare that x is of type Int.

However, we do not specify what the return type is. We can’t — there simply is no syntax for it. Instead, the Kotlin compiler will infer the return type, based on what it knows about what we are returning.

Sometimes, though, Kotlin will not be able to infer what we want. For example, if we dropped the type from the above example:

fun main() {
  val squarifier = { x -> x * x }

  println(squarifier.invoke(3))
}

…we get a compile error: Cannot infer a type for this parameter. Please specify it explicitly.

However, there may be cases where the compiler is happy with the parameter types but cannot infer the return type, or it infers the wrong return type.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.