Accessing Kotlin extension functions from Java

前端 未结 9 1086
梦毁少年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);
    

提交回复
热议问题