In my Java project I have a class where I declare many project constants using public static final String attributes:
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";
...
}
So I can use this in many different places in my project:
...
String userName = user.getProperty(Constants.KIND_NAME);
...
So far I have found some different ways to implement this in Kotlin, like: companion objects or data class. What is the best equivalent code in Kotlin?
@Todd's answer will produce an INSTANCE
instance of class Constants
, which is sometimes unexpected. A better alternative is:
// 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With