Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Functions

Exercise 1 contains

Write a function that takes a list of strings and returns a new list with only the strings that contain the letter 'a'.

Exercise 2 even numbers

Write a function that takes a list of integers and returns a new list with only the even numbers.

Exercise 3 string lengths

Write a function that takes a list of strings and returns a new list with the length of each string.

Exercise 4: Default Parameters

Task: Define a function greet that takes two parameters: a name of type String and a greeting of type String with a default value of "Hello". The function should print a greeting message.

Exercise 5: Named Arguments

Task: Define a function describePerson that takes three parameters: name (String), age (Int), and country (String) with a default value of "unknown". Use named arguments to call this function, specifying age and name but not country.

Exercise 6: Varargs

Task: Write a function sum that accepts an arbitrary number of integer arguments and returns their sum.

Exercise 7: Anonymous Functions and Map

Task: Given a list of integers, use an anonymous function to increment each element by 1, using the map method.

Solutions

Exercise 4: Default Parameters

def greet(name: String, greeting: String = "Hello"): Unit = 
  println(s"$greeting, $name!")

greet("Scala") // Should print "Hello, Scala!"
greet("World", "Hi") // Should print "Hi, World!"

Exercise 5: Named Arguments

def describePerson(name: String, age: Int, country: String = "unknown"): Unit = 
  println(s"$name is $age years old from $country.")

describePerson(age = 25, name = "Alice") // Should print "Alice is 25 years old from unknown."

Exercise 6: Varargs

def sum(numbers: Int*): Int = numbers.sum

println(sum(1, 2, 3, 4)) // Should print 10
println(sum()) // Should print 0

Exercise 7: Anonymous Functions and Map

Task: Given a list of integers, use an anonymous function to increment each element by 1, using the map method.

val numbers = List(1, 2, 3, 4)
val incrementedNumbers = numbers.map(n => n + 1)

println(incrementedNumbers) // Should print List(2, 3, 4, 5)