Is there a way to use Groovy extension methods in Kotlin?

For example, Groovy allows you to get the text of a file, presented java.nio.file.Pathas follows:

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

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

I would like to be able to reuse the Groovy extension method textin Kotlin.

Pay attention . I know. In this particular case, Kotlin has a related method . However, there may be Groovy methods that are useful to Kotlin users.

+4
source share
1 answer

One way is to write a simple wrapper extension function in 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'
}
+4

Source: https://habr.com/ru/post/1625344/


All Articles