简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM