Rahul
Rahul

Reputation: 755

Unable to call kotlin extension function from java

I know kotlin extention functions are compile as static function using fileName as class name with Kt suffix. Problem is my single String parameter function is asking for two String parameters when invoked from java code.

Extention function is in 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: method extractDigits in class KUtilsKt cannot be applied to given types;
required: String,String
found: String
reason: actual and formal argument lists differ in length

Please Help
Thanks

Upvotes: 4

Views: 2606

Answers (1)

Jorn Vernee
Jorn Vernee

Reputation: 33895

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

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

Becomes (javap output):

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

But you're passing only a single argument to the function.

I don't quite understand why you're using an extension function here, I'd expect to see the receiving instance used instead of passing 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 like you tried, and in Kotlin like this:

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

Upvotes: 10

Related Questions