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

Parameters and Return Types

Parameters are the blanks a function asks you to fill, each with a kind, and the return type says what kind of answer comes back. It is like an order form with the type of thing to put in each blank.
Syntax
scala
def function_name(name: String, age: Int): ReturnType = {
  // body
  result
}

Parameters and Return Types

Parameters are declared with a name and type, like (name: String, age: Int), and the return type follows the parameter list after a colon.

Scala can often infer the return type from the body, but explicit return types are recommended for public methods since they document intent and prevent surprising inference results. The last expression in the body is automatically the return value -- an explicit return is rarely used in idiomatic Scala.

Note: Explicit return statements are considered unidiomatic in Scala outside of early-exit edge cases -- let the last expression be the return value instead.

Example: Parameters and Return Types

markup
object Main extends App {
  def add(a: Int, b: Int): Int = {
    a + b
  }

  val result = add(3, 4)
  println(result)
}
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 to give parameter types, as in def add(a, b), which does not compile.
  2. Writing return a + b in a simple function when the last expression is already returned.
  3. Declaring : Int but the last expression returns a String, which gives a type mismatch error.
🔒

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.