In addition to inferring the types of variables, Scala tries to infer the return type of functions and methods. However, there is a catch—it depends on how you define a function. Scala’s return type inference kicks in only if you use an equals sign (=) to separate a method declaration from its body. Otherwise, the method is considered to return a Unit, which is equivalent to Void in Java. Let’s examine the return types of the following functions:

MakingUseOfTypes/functions.scala | |

| def function1 { Math.sqrt(4) } |

| def function2 = { Math.sqrt(4) } |

| def function3 = Math.sqrt(4) |

| def function4 : Double = { Math.sqrt(4) } |

We’ve defined function1 by providing a name and the function body within curly braces. Though syntactically ...

Start Free Trial

No credit card required