Accessing Kotlin extension functions from Java

前端 未结 9 1041
梦毁少年i
梦毁少年i 2020-11-29 21:27

Is it possible to access extension functions from Java code?

I defined the extension function in a Kotlin file.

package com.test.extensions

import c         


        
相关标签:
9条回答
  • 2020-11-29 21:52

    You need to duplicate your functions in the class files:

    Create Kotlin file , for ex Utils.kt

    Enter the code

      class Utils {
                    companion object {
                        @JvmStatic
                        fun String.getLength(): Int {//duplicate of func for java
                            return this.length
                        }
                    }
                }
    
            fun String.getLength(): Int {//kotlin extension function
                return this.length
            }
    

    OR

    class Utils {
        companion object {
    
            @JvmStatic
            fun getLength(s: String): Int {//init func for java
                return s.length
            }
        }
    }
    
    fun String.getLength(): Int {//kotlin extension function
        return Utils.Companion.getLength(this)//calling java extension function in Companion
    }
    

    In kotlin use:

    val str = ""
    val lenth = str.getLength()
    

    In Java use this:

    String str = "";
     Integer lenth = Utils.getLength(str);
    
    0 讨论(0)
  • 2020-11-29 21:54

    As far as I can tell this isn't possible. From my reading of the extensions docs, it appears that

    public fun MyModel.bar(): Int {
        return this.name.length()
    }
    

    creates a new method with the signature

    public static int MyModelBar(MyModel obj) {
        return obj.name.length();
    }
    

    Then, Kotlin maps that function to calls of the form myModel.bar(), where if bar() isn't found in the MyModel class it looks for static methods matching the signature and naming scheme it outputs. Note that this is just an assumption from their statements about extensions being statically imported and not overriding defined methods. I haven't gotten far enough in their source to know for sure.

    So, assuming the above is true there's no way for Kotlin extensions to be called from plain old java code, as the compiler will just see an unknown method being called on an object and error out.

    0 讨论(0)
  • 2020-11-29 22:03

    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());
    
    0 讨论(0)
提交回复
热议问题