Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad a Scala collection for minimum size?

Tags:

scala

How to make sure a Seq is of certain minimum length, in Scala?

The below code does what I want (adds empty strings until arr has three entries), but it feels clumsy.

scala> val arr = Seq("a")
arr: Seq[String] = List(a)

scala> arr ++ Seq.fill(3-arr.size)("")
res2: Seq[String] = List(a, "", "")

A way to fulfill this would be a merger of two sequences: take from first, but if it runs out, continue from second. What was such method called...?

like image 287
akauppi Avatar asked Dec 06 '25 01:12

akauppi


1 Answers

I find this slightly better:

scala> (arr ++ Seq.fill(3)("")).take(3)
res4: Seq[String] = List(a, "", "")

And even better, thanks @thomas-böhm

scala> arr.toArray.padTo(3,"")
res5: Array[String] = Array(a, "", "")
like image 167
akauppi Avatar answered Dec 07 '25 15:12

akauppi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!