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

MyList - step 3

Add method

  • Add the add method
  • Add the + method
  • Create a companion object

Exercise 1

trait MyList[A]:
  ...
  def add(element: A): MyList[A]
  • Give the MyList trait an add method
  • Implement it in Cons and Empty
  • And test it in main with: Empty().add(1).add(2).add(3)

Add method

Empty

override def add(element: A): MyList[A] = Cons(element, this)

Adding an element to Empty means that Empty is not empty anymore and becomes a Cons with the tail Empty (this)

Cons

override def add(element: A): MyList[A] = Cons(element, this)

Adding an element to Cons means adding new head and the tail becomes the current Cons (this)

trait

trait MyList[A]:
  ...
  def add(element: A): MyList[A] = Cons(element, this)

The implementation in Empty and Cons are the same.
So we can move it up to the MyList trait (and remove them from Empty and Cons).
Via inheritance, they are available in Empty and Cons again

main

@main
def main(): Unit =
  val myList: MyList[Int] = Empty().add(1).add(2).add(3)
  println(myList)
  
//  MyList(3, 2, 1)

The order is reversed now.

main

@main
def main(): Unit =
  val myList: MyList[Int] = MyList(1,2,3)
  println(myList)

//  MyList(1, 2, 3)