← Back to Scala Course | Chapter 5: Functions | Lesson 1 of 7

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:

  1. Function Basics
Syntax
scala
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

markup
object Main extends App {
  def greet(): Unit = {
    println("Hello from a function!")
  }

  greet()
  greet()
}
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
  1. Forgetting the = sign in def greet(): Unit = { ... }, which makes it a different syntax or error.
  2. Writing greet without () when it was defined with (), which can give a warning or error in Scala 3.
  3. Defining a function inside an object and calling it before creating the object, when methods on an object are called as Main.greet() from outside.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.