Kotlin 类似于 Groovy 中的作用域函数(let、also、apply、run)

标签 kotlin groovy

我认为标题本身就说明了一切——Groovy 有类似 Kotlin 作用域函数的东西吗?

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

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

最佳答案

Groovy 有 obj.with { } 方法,可以让你做同样的事情:

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

还有 obj.tap { } 变体(相当于 obj.with(true) { })做同样的事情,但它返回传入的对象.

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

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

关于Kotlin 类似于 Groovy 中的作用域函数(let、also、apply、run),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71887133/

相关文章:

Kotlin - 如何根据字符的总长度拆分字符串列表

kotlin - IntelliJ 不会根据 ktlint 的期望对 Kotlin 导入进行排序

android - Jetpack 撰写 : DrawBehind not same height as Button Background

java - 如何避免 Java/Kotlin/IntelliJ IDEA 中的 StackOverFlow 错误?

grails - Groovy getProperties() 调用为不存在的属性调用 getter 超过 1000 次

android - 从 Java 到 Kotlin 的代码转换后的异常 : java. lang.ClassCastException : java. lang.String cannot be cast to com.example.misc.Restaurant

regex - 如何在groovy/gradle中使用正则表达式替换csv中的文本?

loops - 使用循环在 Jenkins 中使用构建流插件运行并行构建

unit-testing - 用多部分请求测试Grails Controller

Groovy URLConnection 获取 4xx 响应的响应