简体   繁体   English

无法从java调用kotlin扩展函数

[英]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. 我知道kotlin扩展函数是作为静态函数编译的,使用fileName作为类名,后缀为Kt。 Problem is my single String parameter function is asking for two String parameters when invoked from java code. 问题是我的单个String参数函数在从java代码调用时要求两个String参数。

Extention function is in KUtils file 扩展函数在KUtils文件中

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 调用java代码

KUtilsKt.extractDigits("99PI_12345.jpg")

Compile Time Error Message : 编译时错误消息:

Error:(206, 42) error: method extractDigits in class KUtilsKt cannot be applied to given types; 错误:(206,42)错误:类KUtilsKt中的方法extractDigits不能应用于给定类型;
required: String,String 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): 成为( javap输出):

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: 然后,在Java中,你可以像你尝试的那样调用它,在Kotlin中就像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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