groovy - 有没有一种干净的方法可以在 Kotlin 中使用 Groovy 的扩展方法?

标签 groovy extension-methods kotlin jvm-languages

例如,Groovy 允许获取由 java.nio.file.Path 表示的文件的文本。如下:

// Groovy code
import java.nio.file.Path
import java.nio.file.Paths

Path p = Paths.get("data.txt")
String text = p.text

我希望能够重用 Groovy 的 text Kotlin 中的扩展方法。

请注意 : 我知道Kotlin has a related method对于这种特殊情况。尽管如此,可能还是有一些对 Kotlin 用户有用的 Groovy 方法。

最佳答案

一种方法是编写一个简单的包装器 extension function在 Kotlin :

// Kotlin code
import org.codehaus.groovy.runtime.NioGroovyMethods

fun Path.text(): String {
  return NioGroovyMethods.getText(this)
}

然后可以像这样使用:

// Kotlin code
import java.nio.file.Path
import java.nio.file.Paths

fun usageExample() {
  val p: Path = Paths.get("data.txt")
  val text: String = p.text()
}

如果使用 Gradle 构建项目,这意味着必须将 Groovy 添加到依赖项中:
// in build.gradle

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.5'
}

关于groovy - 有没有一种干净的方法可以在 Kotlin 中使用 Groovy 的扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34926801/

相关文章:

grails - 从插件访问 'grailsApplication'

groovy - 为了让 groovy 闭包修改委托(delegate)范围内定义的变量,您是否需要显式指定 delegate.theVariableName?

Groovy java.lang.VerifyError - 期望在堆栈上找到整数

windows - Groovy:如何将 .groovy 脚本作为 Windows 服务

.net - 枚举扩展方法

f# - 列表中的扩展方法?

c# - 可以声明一个包含扩展的接口(interface)吗?

android - Recyclerview View 未填充

kotlin - 可变实时数据 : Cannot invoke setValue on a background thread from Coroutine

kotlin - 在 Kotlin 中创建 ehcache 缓存