如何在Groovy闭包中禁用惰性求值[duplicate]

62o28rlo  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(154)

此问题在此处已有答案

Closures in Groovy not capturing outside variables(1个答案)
四个月前关门了。
我的代码是:

def ip_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3' ]
def task = [:]
for (ip in ip_list) {
   task[ip] = { println "test on ${ip}" }
}

for (f in task.values())
{
   f()
 }

输出为:

test on 192.168.1.3
test on 192.168.1.3
test on 192.168.1.3

但我期望的输出是:

test on 192.168.1.1
test on 192.168.1.2
test on 192.168.1.3

我该怎么办?
谢谢你!

bttbmeg0

bttbmeg01#

1

def ip_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3' ]
def task = [:]
for (_ip in ip_list) {
   def ip = _ip
   task[ip] = { println "test on ${ip}" }
}

for (f in task.values())
{
   f()
}

2

def ip_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3' ]
def task = [:]
for (_ip in ip_list) {
   task[_ip] = {ip-> println "test on ${ip}" }.curry(_ip)
}

for (f in task.values()){
   f()
}

3

def ip_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3' ]
def task = {ip-> println "test on ${ip}" }
def task_map = ip_list.collectEntries{ip-> [ip, task.curry(ip)] }

for (f in task_map.values()){
   f()
}

相关问题