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

Parameters and Return Types

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

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.