Calling kotlin functions which are keywords in java from java?

拈花ヽ惹草 提交于 2019-12-04 23:58:54

Since you're trying to use a keyword the compiler won't allow you to use it as a method name

The only workaround I can think is to do something like:

fun new(): String {
    return "just returns some string"
}

fun notAKeyWord() = new()

So you can use WhatEverKt.notAKeyWord() from your java code

For these sorts of problems, you can use the @JvmName annotation.

@JvmName("neww")
fun new(): String {
    return "just returns some string"
}

The name you pass to it will be the name that you can use to refer to the method from Java:

String s = something.neww();

In general, you're probably better off not using Java keywords as Kotlin identifiers if you need to interop with Java code.

You can use @JvmName to provide a different name for your function to be called form Java:

@JvmName("myNew")
fun new(): String {
    return "just returns some string"
}

And the usage in Java:

String bar = foo.myNew();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!