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

Extension Methods

extension

extension(i: Int)
  def print: Unit =
    println(s"some: $i")
@main
def main(): Unit =
  val x = 3
  x.print

generics

extension[A](a: A)
  def print: Unit =
    println(s"some: $a")
@main
def main(): Unit =
  val x = 3
  x.print
  
  val str = "hello"
  str.print

case class

case class Todo(task: String, priority: Int)
object Todo:
  extension(todo: Todo)
    def print: Unit =
      println(s"${todo.priority}. ${todo.task.capitalize}")
@main
def main(): Unit =
  val todoList = List(Todo("walking", 1),Todo("swimming", 2) )
  todoList.foreach(_.print)

// 1. Walking
// 2. Swimming

Scope

The scope rules of extension methods are the simular to the scope of given

  1. imported extension
  2. current scope
  3. companion object

imported extension

object TodoExtension:
  extension (todo: Todo)
    def print: Unit =
      println(s"${todo.priority}. ${todo.task.capitalize}")
@main
def main(): Unit =
  val todoList = List(Todo("walking", 1),Todo("swimming", 2) )
  import TodoExtension.*
  todoList.foreach(_.print)

For extensions the wildcard * import is used.
This is different from to the given import.

Rule of thumb

The rules are similar to the given:

  • Put the most frequently used extension in the companion object
  • Put the other extensions in separate objects with a clear names

Exercises

Exercise 1

val cities = List("London", "Paris", "Lisbon", "Berlin")

Create a list of cities:

  1. In an object create an extension method print to the String class.
  2. In another object create a second extension method print to the String that prints in ALL-CAPS
  3. Choice which print method you will use with an import

Create a case class CapitalCity with a city and a country
Create a list of capital cities

  1. Create an extension method print to the CapitalCity companion object
  2. Print the list of capital cities

Exercise 2

Create a case class Person with a name and age
Create a list of persons

  1. Create an extension method print to the Person companion object.
  2. In another object create an extension method print to the Persion that prints in ALL-CAPS
  3. Choice which print method you will use with an import