Konrad Jamrozik
Konrad Jamrozik

Reputation: 3566

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.

Upvotes: 5

Views: 1295

Answers (1)

Konrad Jamrozik
Konrad Jamrozik

Reputation: 3566

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

Upvotes: 4

Related Questions