typestar

Defining methods in Scala

def with typed parameters and a return type, first as an expression and then as an indented body.

// def name(params): ReturnType = expression
def gramsPerCup(cups: Int): Int = cups * 15

// A body can be any expression, including a call to another def.
def brewWater(cups: Int): Double = gramsPerCup(cups) * 16.0

// An indented body may hold locals; the last expression is the
// result, so there is no return keyword.
def roastNote(minutes: Int, celsius: Int): String =
  val heatIndex = minutes * celsius
  val level =
    if heatIndex < 2000 then "light"
    else if heatIndex < 3400 then "medium"
    else "dark"
  level + " roast"

// Unit means the method is called for its effect, not its value.
def roastBrief(cups: Int): Unit =
  println(s"${gramsPerCup(cups)}g for ${brewWater(cups)}ml")
  println(roastNote(11, 215))

How it works

  1. def gramsPerCup(cups: Int): Int = cups * 15 fits parameters, return type and body on one line.
  2. def brewWater(cups: Int): Double calls the first method, keeping its body a single expression.
  3. roastNote uses an indented body with the locals val heatIndex = minutes * celsius and val level =, and its last expression level + " roast" is the result.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
709
Tokens
113
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 1 of 3 in Functions, step 7 of 27 in Language basics.

← Previous Next →