Home > Software engineering >  Kotlin like scope functions (let, also, apply, run) in Groovy
Kotlin like scope functions (let, also, apply, run) in Groovy

Time:04-16

I think the title speaks for itself - does Groovy have something like Kotlin scope functions?

obj.apply {
  foo()
  bar()
  baz()
}

// is the same as
obj.foo()
obj.bar()
obj.baz()

CodePudding user response:

Groovy has obj.with { } method that allows you to do the same:

obj.with {
  foo()
  bar()
  baz()
}

There is also obj.tap { } variant (an equivalent of obj.with(true) { }) that does the same, but it returns the incoming object.

def newObj = obj.tap {
  foo()
  bar()
  baz()
}

Source: http://docs.groovy-lang.org/docs/next/html/documentation/style-guide.html#_using_with_and_tap_for_repeated_operations_on_the_same_bean

  • Related