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
def gramsPerCup(cups: Int): Int = cups * 15fits parameters, return type and body on one line.def brewWater(cups: Int): Doublecalls the first method, keeping its body a single expression.roastNoteuses an indented body with the localsval heatIndex = minutes * celsiusandval level =, and its last expressionlevel + " roast"is the result.
Keywords and builtins used here
DoubleIntStringUnitbrewWaterdefelsegramsPerCupifroastBriefroastNotethenval
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.
Step 1 of 3 in Functions, step 7 of 27 in Language basics.