![](/img/trans.png)
[英]How to override inherited getter from java class in a kotlin companion object
[英]Accessing a Kotlin object nested in companion object from Java
我在 Kotlin 有這樣的結構
companion object Constants {
/**
* Collection of fields and values relative to phone books.
*/
object PhoneBooks {
/**
* Field indicating the ID of a phone book.
* Each phone book must have an unique ID.
*/
const val PB_ID_KEY = "PB_ID"
/**
* Field indicating the status of phone book.
*/
const val PB_STATUS_KEY = "PB_Status"
/**
* One of the possible [PB_STATUS_KEY] values, when the phone book is in indexing state
* (usually at startup or in update phase).
*/
const val PB_INDEXING = "Indexing"
[...]
問題是我必須有可能從 Java 訪問子對象中的常量值,但這似乎不可能。 我怎樣才能在不改變結構的情況下解決這個問題?
JB Nizet評論道:
在這里工作正常
import static com.yourcompany.yourproject.YourClass.Constants.PhoneBooks;
接着
PhoneBooks.PB_ID_KEY
它對我很有用。 所以我認為讓它作為答案可見是有用的。
在上面的評論中,JB Nizet 展示了如何使用 static 導入來解決問題
但是查看提供的代碼我會使用枚舉
// kotlin
enum class PhoneBooks(val param:String) {
PB_ID_KEY("PB_ID"),
PB_STATUS_KEY("PB_Status"),
PB_INDEXING("Indexing")
}
// java
System.out.println(PhoneBooks.PB_ID_KEY.getParam());
這里的一大優勢是代碼可讀性 PhoneBooks.PB_ID_KEY 以干凈的方式將 PB_ID_KEY 標記為電話簿常量
像 Kotlin 密封類一樣,kolin 編譯器為枚舉添加了一些很好的檢查(詳盡),它們旨在為模式匹配提供干凈可讀的代碼
請參閱@Rolands 在這里回答Kotlin: Using enums with when
嘗試使用界面:)
companion object Constants {
/**
* Collection of fields and values relative to phone books.
*/
interface PhoneBooks {
/**
* Field indicating the ID of a phone book.
* Each phone book must have an unique ID.
*/
const val PB_ID_KEY = "PB_ID"
/**
* Field indicating the status of phone book.
*/
const val PB_STATUS_KEY = "PB_Status"
/**
* One of the possible [PB_STATUS_KEY] values, when the phone book is in indexing state
* (usually at startup or in update phase).
*/
const val PB_INDEXING = "Indexing"
[...]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.