Learn/Scala/6. Functions
Lesson 6 of 8
Sign in

Scala, lesson 6

Functions

A function packs a piece of logic under a name so you can reuse it and test it on its own. In Scala you define one with def (Scala calls these methods, even at the top level of a file).

Breaking it down:

  • square is the name.
  • (n: Int) is the parameter list. Parameters must have a type.
  • : Int after the parentheses is the return type.
  • After = comes the body. Its value is the result; there is no need for return.

Longer bodies

When the body needs several steps, put it on indented lines. The value of the last expression is what the method returns:

Scala does have a return keyword, but idiomatic code almost never uses it. Since and are expressions, they make natural method bodies:

2 exercises to try what you just read.

Exercise 1

Shipping costs

Press Ctrl Enter or Check to test your code.

Exercise 2

Party bags

Press Ctrl Enter or Check to test your code.

if
match

Several parameters and default values

Separate parameters with commas. You can give a parameter a default value, and callers can name arguments to make a call clearer:

Methods that only do something

A method that prints instead of computing a value returns Unit:

Try to keep calculations and printing separate: one method works out the answer, another displays it. Calculation methods are much easier to reuse.

Scope

A name defined inside a method (a parameter or a local val) exists only inside that method. Two methods can each have their own total without clashing. Names defined at the top level of the file are visible to every method in it.

Recursion

A method can call itself. Scala needs the return type written out for recursive methods, because it can't infer a type that depends on itself:

Further reading

  • Scala 3 Book: Methods
  • Scala 3 Book: Method features

Write def shippingCost(weight: Int): Int using these rules:

  • up to 1 kg: 5
  • up to 5 kg: 12
  • up to 20 kg: 25
  • over 20 kg: 25 plus 2 for every kg above 20

The first input line is the number of parcels. Each following line holds one whole-number weight. For each parcel print <weight> kg costs <cost>, then print Total: <sum>.

Sample input:

Sample output:

You have some candies and some stickers and want to fill as many identical party bags as possible, using everything. The number of bags is the greatest common divisor (GCD) of the two amounts.

Write a recursive def gcd(a: Int, b: Int): Int using Euclid's rule: the GCD of a and 0 is a; otherwise the GCD of a and b equals the GCD of b and a % b.

Read the candies and the stickers (two whole numbers, at least 1, on one line separated by a space) and print:

Sample input:

Sample output:

def square(n: Int): Int = n * n

@main def demo(): Unit =
  println(square(7))   // 49
def priceWithTax(price: Double, taxRate: Double): Double =
  val tax = price * taxRate
  price + tax
def ticketPrice(age: Int): Int =
  if age < 12 then 5
  else if age >= 65 then 6
  else 10
def greet(name: String, greeting: String = "Hello"): String =
  s"$greeting, $name!"

greet("Ada")                       // Hello, Ada!
greet("Ada", "Welcome")            // Welcome, Ada!
greet(greeting = "Hi", name = "Ada")
def banner(title: String): Unit =
  println("=" * title.length)
  println(title)
  println("=" * title.length)
def area(w: Int, h: Int): Int =
  val result = w * h
  result
// `result` and `w` don't exist out here
def factorial(n: Int): Long =
  if n <= 1 then 1 else n * factorial(n - 1)
3
1
4
23
1 kg costs 5
4 kg costs 12
23 kg costs 31
Total: 48
Bags: <n>
Each bag: <c> candies, <s> stickers
12 18
Bags: 6
Each bag: 2 candies, 3 stickers