Scala Notes — Function Return Types

Ash
1 min readApr 11, 2020

Function Return Type

Return type is optional, but it’s better to declare it because compiler may not be able to infer it to the intended type.
For the sake of simplicity here’s an example in which the function returns Int or Boolean so compiler infers it to be AnyVal

scala> def func1(x: Int) = if (x > 1) x else falsefunc1: (x: Int)AnyVal

But if you declare it to be Int explicitly then compiler throws an error and helps you catch the bug.

Scala> def func1(x: Int): Int = if (x > 1) x else false<console>:11: error: type mismatch;found   : Boolean(false)required: Intdef func1(x: Int): Int = if (x > 1) x else false                                           ^

If you don’t return anything from a function the compiler assigns it a return type of Unit. This is another reason where declaring a return type helps you catch a bug.

scala> def func1(x: Int): Int = println(x)<console>:11: error: type mismatch;found   : Unitrequired: Intdef func1(x: Int): Int = println(x)                                ^

--

--