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

Function Basics

In this page:

  1. Function Basics

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()
}
🔒

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.