Accessing Kotlin Extension Functions From Java


Answer :

All Kotlin functions declared in a file will be compiled by default to static methods in a class within the same package and with a name derived from the Kotlin source file (First letter capitalized and ".kt" extension replaced with the "Kt" suffix). Methods generated for extension functions will have an additional first parameter with the extension function receiver type.

Applying it to the original question, Java compiler will see Kotlin source file with the name example.kt

package com.test.extensions  public fun MyModel.bar(): Int { /* actual code */ } 

as if the following Java class was declared

package com.test.extensions  class ExampleKt {     public static int bar(MyModel receiver) { /* actual code */ } } 

As nothing happens with the extended class from the Java point of view, you can't just use dot-syntax to access such methods. But they are still callable as normal Java static methods:

import com.test.extensions.ExampleKt;  MyModel model = new MyModel(); ExampleKt.bar(model); 

Static import can be used for ExampleKt class:

import static com.test.extensions.ExampleKt.*;  MyModel model = new MyModel(); bar(model); 

Kotlin top-level extension function are compiled as Java static methods.

Given Kotlin file Extensions.kt in package foo.bar containing:

fun String.bar(): Int {     ... } 

The equivalent Java code would be:

package foo.bar;  class ExtensionsKt {     public static int bar(String receiver) {          ...     } } 

Unless, that is, Extensions.kt contained the line

@file:JvmName("DemoUtils") 

In which case the Java static class would be named DemoUtils

In Kotlin, extension methods can be declared in other ways. (For example, as a member function or as an extension of a companion object.)


I have a Kotlin file called NumberFormatting.kt that has the following function

fun Double.formattedFuelAmountString(): String? {     val format = NumberFormat.getNumberInstance()     format.minimumFractionDigits = 2     format.maximumFractionDigits = 2     val string = format.format(this)     return string } 

In java I simple access it over the file NumberFormattingKt in the following way after the required import import ....extensions.NumberFormattingKt;

String literString = NumberFormattingKt.formattedFuelAmountString(item.getAmount()); 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable