簡體   English   中英

我可以使用Kotlin隨播對象方法隱藏Java靜態方法嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM