Can't call kotlin extension function from java

I know kotlin extension functions are compiled as static functions using fileName as the class name suffixed with Kt. The problem is my only String parameter function asks for two String parameters when called from java code.

The extension function is in the KUtils file

fun String.extractDigits(strValue: String): String {
    val str = strValue.trim { it <= ' ' }
    var digits = ""
    var chrs: Char
    for (i in 0..str.length - 1) {
        chrs = str[i]
        if (Character.isDigit(chrs)) {
            digits += chrs
        }
    }
    return digits
}

      

Calling java code

KUtilsKt.extractDigits("99PI_12345.jpg")

      

Compile time error message:

Error: (206, 42) error: The extractDigits method in the KUtilsKt class cannot be applied to the specified types; required: String, String
found: String
reason: actual and formal argument lists differ in length

Please help
Thanks

+3


source to share


1 answer


The problem is that the receiving instance is encoded as a parameter. So:

fun String.extractDigits(strValue: String): String {...}

      

It becomes ( javap

conclusion):

public static final java.lang.String extractDigits(java.lang.String, java.lang.String);

      

But you are only passing one argument to the function.



I don't quite understand why you are using the extension function here, I would expect to see the receive instance being used instead of passing in a separate value:

fun String.extractDigits(): String {
    val str = this.trim { it <= ' ' } // Using `this`, i.e. the receiving instance
    var digits = ""
    var chrs: Char
    for (i in 0..str.length - 1) {
        chrs = str[i]
        if (Character.isDigit(chrs)) {
            digits += chrs
        }
    }
    return digits
}

      

Then, in Java, you can call it as you tried, and in Kotlin:

val str = "123blah4"
println(str.extractDigits()) // prints 1234

      

+8


source







All Articles