Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Java's 'public static final string'

Tags:

kotlin

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?

like image 548
Carlos Eduardo Ki Lee Avatar asked Jun 10 '18 12:06

Carlos Eduardo Ki Lee


1 Answers

@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"
like image 83
ice1000 Avatar answered Oct 07 '22 12:10

ice1000