在这种情况下如何与with语句一起使用?

时间:2019-12-23 13:32:26

标签: groovy

我有类似的东西

def firstName = apiAccessor.getIdentityAPI().getUser(commentInput.authorId).firstName
def lastName = apiAccessor.getIdentityAPI().getUser(commentInput.authorId).lastName
commentVar.authorFullName = firstName + " " + lastName

它可以工作,但是我想用语句使同样的事情变得有用。

我尝试过,但是不起作用:

with(apiAccessor.getIdentityAPI().getUser(commentInput.authorId)) {
    commentVar.authorFullName = it.firstName + " " + it.lastName
}

看起来如何?

1 个答案:

答案 0 :(得分:0)

您调用.with{ ... }(或.tap{ }) right on the thing you want to use inside the closure. It's an delegate, so you don't even have to use it`(或命名参数)。

您的代码非常接近:

def data = [a: [b: [c: [firstName: "X", lastName: "Y"]]]]
def commentVar = [:]

data.a.b.c.with {
    commentVar.authorFullName = firstName + " " + lastName
}

assert commentVar.authorFullName == "X Y"