irrelevantUser
irrelevantUser

Reputation: 1322

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.

Upvotes: 2

Views: 561

Answers (2)

marstran
marstran

Reputation: 28066

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)

Upvotes: 4

prayagupadhyay
prayagupadhyay

Reputation: 31262

You can use .padTo,

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.take(5).padTo(len = 5, elem = 0)
res5: List[Int] = List(1, 2, 3, 0, 0)

similar question: Scala - Pad an array to a certain size

You can also write extension method takeOrElse on List[Int],

scala>     implicit class ListOps(list: List[Int]) {
     |       def takeOrElse(length: Int, elem: Int): List[Int] = {
     |         list.take(length).padTo(len = length, elem = elem)
     |       }
     |     }
defined class ListOps

scala> val newList = l.takeOrElse(5, 0)
newList: List[Int] = List(1, 2, 3, 0, 0)

Also see: Scala extension methods?

Upvotes: 3

Related Questions