[英]Generating random values with Scala
I am using this method to generate a random token in Scala: 我正在使用此方法在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. 您的
randomString
可以正常工作。 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. default[A](mapping: Mapping[A], value: A)
方法是从randomString(...)(...)
获取一个值,并且该值保留在刚创建的Form
中。 So userForm
will use the same random token every time it has use the default. 因此,
userForm
每次使用默认值时都将使用相同的随机令牌。
Were you to create a new Form
every time then you would not have this problem. 如果您每次都创建一个新
Form
那么您将不会遇到此问题。 This would be as easy as changing val
to def
. 这就像将
val
更改为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. 替代方法是创建自己的
Mapping
,该Mapping
充当default
行为,但将thunk作为第二个参数。
scala.util.Random
is using java.util.Random
for generating random numbers. scala.util.Random
使用java.util.Random
生成随机数。 ju.Random
is using 48 bit seed for generating random numbers. ju.Random
正在使用48位种子生成随机数。 If you create two instances of Random
with same seed (as in your case) they'll return same sequence of random numbers. 如果您创建两个具有相同种子的
Random
实例(如您的情况),它们将返回相同的随机数序列。
You should create Random
class with non default constructor that takes seed number. 您应该使用带有种子编号的非默认构造函数创建
Random
类。 For ex. 对于前。 you can use
currentTimeMillis
for seed. 你可以使用
currentTimeMillis
种子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.