![](/img/trans.png)
[英]What is the difference between Java static method and Kotlin companion object ? Why it is giving error in Andorid Data Binding?
[英]Can I hide a Java static method with a Kotlin companion object method?
我正在嘗試向我的應用程序添加一些特定於類的功能,並且希望在類層次結構中具有靜態方法,其中每個類都實現自己的方法版本。 我知道將它們視為替代會產生難以預測的行為,但我打算僅以類名作為前綴來調用方法。 像
// 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基類的靜態方法嗎?
這是整個錯誤:
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 interop在幕后工作的一個問題。 如果要防止錯誤,可以添加@JvmName批注以在JVM中使用另一個名稱:
// Kotlin
class Child: Base() {
companion object {
@JvmStatic
@JvmName("childMapString")
fun mapString(s: String): Int {
return when {
"a" -> 1
else -> -1
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.