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

Exercises

Exercise 1: Add two Option number

def addOptions(optA: Option[Int], optB: Option[Int]): Option[Int] 

Use pattern matching and for comprehension

(Extra) Use map and flatMap

Exercise 2: Read a file

Read from file

with try-catch

def readFileWithTryCatch(filePath: String): String 

with Try, Success and Failure

def readFileWithTry(filePath: String): Try[String] 

Exercise 3: Login with password check

Implement a simple login function using Either.

  • Left will return an error message if the login fails,
  • Right will return a welcome message upon successful login.
  def login(username: String, password: String): Either[String, String] 

Exercise 2: Option for Handling Nulls

Task: Given a method that might return null, adapt it to return an Option of its result instead. Assume the method signature is def getUser(id: Int): User, where User is a class and getUser might return null.

def getUserById(id: Int): Option[User]

Write a main function that uses this function

Exercise 5: Using Option with Collections

Task: Write a function that receives a list of Option[Int] and returns a new list with all None values removed and doubles each Some value.

def processOptions(options: List[Option[Int]]): List[Int] = options.flatten.map(_ * 2)

// Test cases
val optionsList = List(Some(1), None, Some(2), None, Some(3))
println(processOptions(optionsList))  // Should print: List(2, 4, 6)