【问题标题】:Is there a clean way to use Groovy's extension methods in Kotlin?有没有在 Kotlin 中使用 Groovy 扩展方法的干净方法?
【发布时间】:2016-01-21 14:45:24
【问题描述】:

例如,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 has a related method。尽管如此,还是有一些对 Kotlin 用户有用的 Groovy 方法。

【问题讨论】:

    标签: groovy extension-methods kotlin jvm-languages


    【解决方案1】:

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

    // 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'
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2015-11-11
      • 2020-02-26
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多