Reputation: 2429
There's data I need to split into columns. The empty spaces must be distributed among the final columns. So if I have four elements and three columns, the columns will have these number of elements: 2, 1 and 1.
I need to know how many columns will be full. The answer is:
val full = data.length % NUMBER_OF_COLUMNS
The problem with that is that the number of items is a multiple of the number of columns, this returns zero, which is not what I want. So I could do:
val full = if (data.length % NUMBER_OF_COLUMNS == 0) NUMBER_OF_COLUMNS else
data.length % NUMBER_OF_COLUMNS
This works, but does not feel very "Scala-like." It's definitely verbose and clumsy and the remainder operation either needs to be stored or performed twice. (Here, I picked the latter option.)
Is there a better way?
In Python, what I'd do is basically use the or
operator with an Int
, like this:
full = len(data) % NUMBER_OF_COLUMNS or NUMBER_OF_COLUMNS
Done. But I can't think of something similar in Scala. Does it not exist or am I simply not seeing it?
Upvotes: 3
Views: 111
Reputation: 20415
Using pattern matching like this
len % nCols match {
case 0 => nCols
case v => v
}
Note the second pattern matches any (non zero) value and delivers the mod value already calculated.
Upvotes: 5