Categories
Programming

Simple Way to Add a Global Constants File with Kotlin

One of the most common things I’m adding when making an Android app is a file that contains various constant values to be used in various places. Here’s how I’d set it up.

First, create the .kt file (usually I’d name it Constants.kt). Add the package name at the top, then add the constant variables without creating any class for them. In this example I assume that the file is on the root folder of the app. For example:

package studio.oldblack.wpflightcontrol
const val WPFC_SHARED_PREFS_FILENAME = "wpfc_prefs"
const val WPFC_WPCOM_AUTH_ENDPOINT = "https://public-api.wordpress.com/oauth2/authorize"
const val WPFC_WPCOM_TOKEN_ENDPOINT = "https://public-api.wordpress.com/oauth2/token"
view raw constants.kt hosted with ❤ by GitHub
Gist containing the Constants.kt file example

Finally, to use the constants themselves, we can just write the name without any fuss (on line 2 on the example below):

val sharedPreferences = EncryptedSharedPreferences.create(
WPFC_SHARED_PREFS_FILENAME,
masterKeyAlias,
this,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
Example of how to use a constant variable

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s