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