Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example, Groovy allows to get text of a file represented by java.nio.file.Path as 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 Groovy's text extension method in Kotlin.

Please note: I know Kotlin has a related method for this particular case. Still, there might be Groovy methods which are useful for Kotlin users.

like image 655
Konrad Jamrozik Avatar asked Sep 25 '22 14:09

Konrad Jamrozik


1 Answers

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)
}

Which then can be used like:

// 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()
}

If using Gradle to build the project, this means Groovy has to be added to dependencies:

// in build.gradle

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.5'
}
like image 194
Konrad Jamrozik Avatar answered Sep 28 '22 03:09

Konrad Jamrozik