Scala take example

The “take” method lets you pull a few items from a list:

List(1, 2, 3, 4, 5).take(3)

res6: List[Int] = List(1, 2, 3)

If you want to pull these from the other end of the list, you can use takeRight:

List(1, 2, 3, 4, 5).takeRight(3)

res8: List[Int] = List(3, 4, 5)

Similarly, you can use “takeWhile” to pull items until a condition is met:

Stream.
  from(1).
  takeWhile(_ < 5).
  toList

res6: List[Int] = List(1, 2, 3)

Leave a Reply

Your email address will not be published. Required fields are marked *