Return Type Inference

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 ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.