Function Basics
In this page:
Function Basics
A Scala function (or method, when defined inside a class/object) is declared with def name(params): ReturnType = body. When the body is a single expression, the = sign directly assigns its value as the return value, without needing braces or a return keyword. Functions are called by name, just like any built-in operation.
Note: For a single-expression function body, braces are optional: def square(n: Int): Int = n * n is complete on one line.
Example: Function Basics
object Main extends App {
def greet(): Unit = {
println("Hello from a function!")
}
greet()
greet()
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: