5
votes

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?

2
I want to emulate: public static finalCarlos Eduardo Ki Lee
use object to declare your constants class. and define all as const valViktor Yakunin

2 Answers

10
votes

@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"
0
votes

You would want to use a simple class with a compaion object and some const vals:

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"
    }
}