O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required