assign “it” in each iteration (groovy)

后端 未结 5 1947
粉色の甜心
粉色の甜心 2021-02-20 03:32

Hey, i try to trim each string item of an list in groovy

list.each() { it = it.trim(); }

But this only works within the closure, in the list th

相关标签:
5条回答
  • 2021-02-20 03:55

    According to the Groovy Quick Start, using collect will collect the values returned from the closure.

    Here's a little example using the Groovy Shell:

    groovy:000> ["a    ", "  b"].collect { it.trim() }
    ===> [a, b]
    
    0 讨论(0)
  • 2021-02-20 03:57
    list = list.collect { it.trim() }
    
    0 讨论(0)
  • 2021-02-20 03:58

    @sepp2k i think that works in ruby

    and this works in groovy list = list.collect() { it.trim(); }

    0 讨论(0)
  • 2021-02-20 04:06

    If you really had to modify the list in place, you could use list.eachWithIndex { item, idx -> list[idx] = item.trim() }.

    collect() is way better.

    0 讨论(0)
  • 2021-02-20 04:12

    You could also use the spread operator:

    def list = [" foo", "bar ", " groovy "]
    list = list*.trim()
    assert "foo" == list[0]
    assert "bar" == list[1]
    assert "groovy" == list[2]
    
    0 讨论(0)
提交回复
热议问题