4

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

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

1 Comment

I use a library which has an extension function. I'm not able access that extension function in java classes, meaning that the corresponding java class file is not created. But, I'm able to access it in Kotlin classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.