Generate alphanumeric string

11,868

Solution 1

Use .mkString("") to create a String from the Stream :

scala> val company = s"rnd_company_${Random.alphanumeric take 10 mkString}"
company: String = rnd_company_BbesF0EY1o

Solution 2

You have an example here

scala> val x = Random.alphanumeric
x: scala.collection.immutable.Stream[Char] = Stream(Q, ?)

scala> x take 10 foreach println
Q
n
m
x
S
Q
R
e
P
B

So you can try this:

   import scala.util.Random 
   val company = s"rnd_company_${(xx take 10).mkString}"
Share:
11,868

Related videos on Youtube

FelixHJ
Author by

FelixHJ

Scala/AKKA developer in telecom. Interested in functional programming, networking stuff, security.

Updated on September 16, 2022

Comments

  • FelixHJ
    FelixHJ over 1 year

    I need some test company-names, like "rnd_company_blah23haf9", "rnd_company_g356fhg57" etc.

    Is it possible to do something like

    import scala.util.Random
    val company = s"rnd_company_${Random.alphanumeric take 10 ?????}"
    

    provided someone can fill out ????? of course.

  • FelixHJ
    FelixHJ almost 9 years
    That was exactly the example I started with. There is something missing in your code (Random.*)?
  • Carlos Vilchez
    Carlos Vilchez almost 9 years
    I forgot to add it to the example. Thanks
  • Wolfsblvt
    Wolfsblvt about 8 years
    Sidenote: My compiler tells me to remove the unnecessary parantheses at "". So you can just write take 10 mkString "".
  • Andrii Abramov
    Andrii Abramov over 6 years
    No need in explicitly specifying empty string. Just Random.alphanumeric take 10 mkString