Defining functions with def
def name(param: Type, ...): ReturnType = body defines a function. Parameters always need their types; the return type can usually be inferred from the body. The body is an expression — often a single line — and its value is what the function returns. There is no need for return. A multi-line body is an indented block, and its last expression is the result.
def square(x: Int): Int = x * x
def area(width: Double, height: Double) = width * height
def greet(name: String): Unit =
println(s"Hello, $name")
def describe(n: Int): String =
val sign = if n < 0 then "negative" else "non-negative"
s"$n is $sign"
@main def run(): Unit =
println(square(7))
println(area(2.5, 4))
greet("Asha")
println(describe(-3))49
10.0
Hello, Asha
-3 is negativearea has no declared return type — the compiler infers Double. area(2.5, 4) passes an Int where a Double is expected; Scala widens it for you because no precision is lost.
Write def isAdult(age: Int): Boolean and call it with 17 and 18.
Recursive method needs return type
def factorial(n: Int) =
if n <= 1 then 1 else n * factorial(n - 1)
@main def run(): Unit =
println(factorial(5))-- [E044] Cyclic Error: Main.scala:2:28
2 | if n <= 1 then 1 else n * factorial(n - 1)
| ^
| Overloaded or recursive method factorial needs return type
|
| Run with -explain-cyclic for more details.
1 error found
Compilation failedTo infer the return type the compiler has to type the body, but the body calls factorial, whose type is the very thing it is trying to work out. It refuses to guess.
Declare the return type on every recursive (and overloaded) method.
def factorial(n: Int): Int =
if n <= 1 then 1 else n * factorial(n - 1)
@main def run(): Unit =
println(factorial(5))