Groovy在Map和Closure之间转换

wr98u20j  于 2023-04-19  发布在  其他
关注(0)|答案(2)|浏览(126)

所以我知道我可以将Closure(cdata)转换为Map(toObj)如下:

Closure cdata = {
    a = 1
    b = 2   
    c = 3
}
Map toObj = [:]
cdata.resolveStrategy = Closure.DELEGATE_FIRST
cdata.delegate = toObj
cdata()
println(toObj)

输出[a:1, b:2, c:3]
但是我的问题是如何正确地将Map转换为Closure呢?这看起来“有效”,但它并没有采用相同的方法

Map mdata = ["a":1, "b":2, "c":3]
Closure toClos = {}
mdata.every { toClos[it.key] = it.value }

这里有没有更正确的对象转换方法?

zkure5ic

zkure5ic1#

好吧...这样如何?

// Given a map, return a closure that sets properties on the delegate
def makeClosure(Map m) {
    { ->
        m.each { k, v ->
            delegate."$k" = v
        }
    }
}

// Generate a closure from our map of keys
Map mdata = [ a: 1, b: 2, c: 3 ]
def clos = makeClosure(mdata)

// Some imagined class for testing
@groovy.transform.ToString
class SomeClass {
    Integer a = 0
    Integer b = 0
    Integer c = 0
}

def d = new SomeClass()

// Set the delegate to our imagined class
clos.delegate = d
clos.resolveStrategy = Closure.DELEGATE_FIRST

// And call the closure
clos()

// Prints SomeClass(1, 2, 3)
println d

然而,所有这些都可以通过简单地执行以下操作来避免:

Map mdata = [ a: 1, b: 2, c: 3 ]

def d = new SomeClass(mdata)

println d
h79rfbju

h79rfbju2#

奇怪的问题

Map m = [a:1,b:2,c:3]
Closure mapper = { src, dst ->
        src.each{ k,v -> dst[k] = v }
        return dst
    }.curry(m)

//test
def obj2 = mapper( [x:0] )
println(obj2)
assert [x:0,a:1,b:2,c:3]==obj2

相关问题