Function Basics
A function is a named recipe you write once and use whenever you like. In Scala you write def, give it a name, and describe the steps.
In this page:
Syntax
def function_name(param: Type): ReturnType = {
// body
result
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting the
=sign indef greet(): Unit = { ... }, which makes it a different syntax or error. - Writing
greetwithout()when it was defined with(), which can give a warning or error in Scala 3. - Defining a function inside an
objectand calling it before creating the object, when methods on anobjectare called asMain.greet()from outside.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: