'Scala generate a collection of elements based on a number of required elements and a known first element
Looking for an elegant Scala way to generate a collection of elements based on a number of required elements and a known first element.
For example:
def generateListOfData(numberOfElements: Int = 1): Seq[Data] = {
if(numberOfElements == 1)
Seq(aData(id = id)) //aData is some builder
else
// generate a `Seq` of elements with `id = randomInt`
}
What would be the most elegant approach to do it?
Solution 1:[1]
You can generate range from 1 to numberOfElements - 1 map it into Data and prepend with default element:
def generateListOfData(numberOfElements: Int = 1): Seq[Data] = {
if (numberOfElements > 0) {
val rnd = new scala.util.Random
aData(id = id) +: (1 to numberOfElements - 1)
.map(_ => aData(id = rnd.nextInt()))
}
Seq[Data]()
}
Or using foldLeft and pattern matching with guards:
def generateListOfData(numberOfElements: Int = 1): Seq[Data] = {
val rnd = new scala.util.Random
numberOfElements match {
case _ if numberOfElements > 0 => (1 to numberOfElements - 1)
.foldLeft(Seq(aData(id = id))) { (acc, _) => aData(id = rnd.nextInt()) +: acc }
.reverse
case _ => Seq()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
