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 5

Concat and Flatmap

We will add two new methods to MyList

  • ++ (concatenation)
  • flatMap

Exercise

trait MyList[A]:
  ...
  infix def ++(other: MyList[A]): MyList[A]
  def flatMap[B](f: A => MyList[B]): MyList[B]

main

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

  println( myList ++ otherList )

  println( myList.flatMap(a => MyList(a, a + 1)) )

// MyList(1, 2, 3, 4, 5)
// MyList(1, 2, 2, 3, 3, 4)