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
imported extensioncurrent scopecompanion 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:
- In an object create an extension method
printto theStringclass. - In another object create a second extension method
printto the String that prints in ALL-CAPS - Choice which
printmethod you will use with animport
Create a case class CapitalCity with a city and a country
Create a list of capital cities
- Create an extension method
printto the CapitalCity companion object - Print the list of capital cities
Exercise 2
Create a case class Person with a name and age
Create a list of persons
- Create an extension method
printto the Person companion object. - In another object create an extension method
printto the Persion that prints in ALL-CAPS - Choice which
printmethod you will use with animport