A Scala function to generate a random-length string with blank spaces

As a brief note today, here’s a Scala method to generate a random string that is random length and also contains blank spaces:

def genRandomVariableLengthStringWithBlankSpaces(r: scala.util.Random): String = {
    val ab = ArrayBuffer[Char]()
    val maxLength = r.nextInt(100) + 50  //range of 50-149
    for (i <- 1 to maxLength) {
        if (i % 5 == 0)
            ab.append(' ')
    val charSeq: mutable.Seq[Char] = Random.shuffle(ab)
    charSeq.mkString + "\n"

I created this because the methods in the Scala Random class don’t work for what I need today, which is a string with a lot of blank spaces in it. I’m sure the code can be improved but I’m on a tight deadline today and this is what I came up with in the time allotted.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.