生成随机数并传递给 Groovy 中的方法

Generate random numbers and pass to method in Groovy

我有 select(int a, int b, int c) 方法,我想向它传递 3 个随机生成的值和 select()。所以我这样做:

public void select() {
        Random random = new Random()
        def values= []
        (1..3).each {
            values<< random.nextInt(100 + 1)
        }
        select(values[0], values[1], values[2])
    }

但这是 Groovy 代码,我想缩短它。我该怎么做我可以做类似的事情吗(我不能但是如何将其修改为运行):

public void select() {
              select((1..3).each {
            values<< random.nextInt(100 + 1)
        }
    }

你可以这样做:

def select() {
    select(*new Random().with { r -> (1..3).collect { r.nextInt() } })
}

或者,如果您不喜欢 with,并希望它更具解释性:

def select() {
    def r = new Random()
    def args = (1..3).collect { r.nextInt() }
    select(*args)
}

如果您使用 Java 8,您可以使用产生无限流的 Random.ints() 方法,并使用 limit(3) 查看前三个:

def select() {
    select(*new Random().ints().limit(3).toArray())
}

再次使用 splat 运算符来展平数组