有没有一种干净的方式在Kotlin中使用Groovy的扩展方法?

例如,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 

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

请注意 :我知道Kotlin在这个特殊情况下有一个相关的方法 。 不过,可能有Groovy方法对Kotlin用户很有用。

一种方法是在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' }