我正在尝试向我的应用程序添加一些特定于类的功能,并且我希望在类层次结构上有静态方法,其中每个类实现其自己版本的方法。我知道将这些视为重写将产生难以预测的行为,但我打算只调用以类名为前缀的方法。太像了
// Java
public class Base {
public static int mapString(@NonNull String s) {
int value = Child.mapString(s);
if (value < 0) {
return defaultValue;
}
}
}
// Kotlin
class Child: Base() {
companion object {
@JvmStatic fun mapString(s: String): Int {
return when {
"a" -> 1
else -> -1
}
}
}
}
像这样,Android Studio抱怨Child.mapString()意外重写,但是如果我添加override
关键字,那么Android Studio会抱怨没有找到重写的东西。
我可以对Kotlin隐藏Java基类的静态方法吗?
发布于 2018-07-26 05:26:15
这是一个完整的错误:
Accidental override: The following declarations have the same JVM signature (mapString(Ljava/lang/String;)I):
fun mapString(s: String): Int defined in com.example.Base
fun mapString(s: String): Int defined in com.example.Child
这可能是Kotlin如何在幕后使用Java互操作的问题。如果您想防止该错误,可以在JVM中添加@JvmName注释以具有另一个名称:
// Kotlin
class Child: Base() {
companion object {
@JvmStatic
@JvmName("childMapString")
fun mapString(s: String): Int {
return when {
"a" -> 1
else -> -1
}
}
}
}
https://stackoverflow.com/questions/51526525
复制相似问题