scalalistcollectionstake

Scala - List take - OrElse - with default value


I am trying to implement a way to take n from a Scala List, but if n > list.length, specify a default value. Something like takeOrElse.

Say, val l = List(4, 6, 10)

val taken = l.takeOrElse(5, 0) //List(4, 5, 6, 0, 0)

Is there a way to do this idiomatically without mutation and buffers? Appreciate your inputs.


Solution

  • You can use the take and padTo functions on List.

    The take returns a new List with the n first elements of the list, or the whole list if n was less than the length of the list.

    The padTo function will add elements to the List until its length is equal to the value in its first parameter. It will do nothing if the list is already long enough.

    Like this:

    val taken = l.take(5).padTo(5, 0)