在我的Java项目中,我有一个类,我使用 public static final String 属性声明了许多项目常量:
public class Constants {
public static final String KIND_NAME = "user";
public static final String AVATAR_IMAGE_ID = "avatarImageId";
public static final String AVATAR_IMAGE_URL = "avatarImageUrl";
public static final String NAME_COLUMN = "name";
public static final String TOTAL_SCORE_COLUMN = "totalScore";
...
}
所以我可以在项目的许多不同地方使用它:
...
String userName = user.getProperty(Constants.KIND_NAME);
...
到目前为止,我已经找到了一些在Kotlin中实现此方法的不同方法,例如:伴侣对象或数据类。什么是Kotlin中最好的等效代码?
答案 0 :(得分:10)
@Todd的回答将产生INSTANCE
类Constants
的实例,这有时会出乎意料。更好的选择是:
// file-level
@file:JvmName("Constants")
const val KIND_NAME = "user"
const val AVATAR_IMAGE_ID = "avatarImageId"
const val AVATAR_IMAGE_URL = "avatarImageUrl"
const val NAME_COLUMN = "name"
const val TOTAL_SCORE_COLUMN = "totalScore"
答案 1 :(得分:0)
您可能希望使用简单的class
与compaion object
和一些const val
s:
class Constants {
companion object {
const val KIND_NAME = "user"
const val AVATAR_IMAGE_ID = "avatarImageId"
const val AVATAR_IMAGE_URL = "avatarImageUrl"
const val NAME_COLUMN = "name"
const val TOTAL_SCORE_COLUMN = "totalScore"
}
}