简体   繁体   中英

Generating random values with Scala

I am using this method to generate a random token in Scala:

  def randomString(alphabet: String)(n: Int): String =
    Stream.continually(Random.nextInt(alphabet.size)).map(alphabet).take(n).mkString

I use this method to generate a default value for a form:

  val userForm = Form(
    mapping(
      "token" -> default(text, (randomString("0123456789abcdef")(40))),
      "username" -> optional(text),
      "email" -> email,
      "password" -> nonEmptyText,
      "gender" -> nonEmptyText
    )(User.apply)(User.unapply)
  )

Why do I always get the same token when running this code?

Your randomString works as expected. The problem is with how you're using it.

The default[A](mapping: Mapping[A], value: A) method is getting a value from randomString(...)(...) and that value stays with the Form that you've just created. So userForm will use the same random token every time it has use the default.

Were you to create a new Form every time then you would not have this problem. This would be as easy as changing val to def . But there is certainly a better way to do it.


The alternative would be to create your own Mapping that acts default but takes a thunk as its second argument.

scala.util.Random is using java.util.Random for generating random numbers. ju.Random is using 48 bit seed for generating random numbers. If you create two instances of Random with same seed (as in your case) they'll return same sequence of random numbers.

You should create Random class with non default constructor that takes seed number. For ex. you can use currentTimeMillis for seed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM