Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare constants in kotlin similar to Java [duplicate]

Tags:

android

kotlin

  • In Java class, I usually declare all my constants in a single constant file and access across the project
  • How to achieve the same in kotlin

Java Code:

public class LinksAndKeys {
    public static String BASE_URL = "http://11.111.111.11:8000/";
    public static double TAXABLE_AMOUNT = 0.18;
    public static int DAYS_INTERVAL_FOR_RATE_ME_DIALOG = 50000;
}

*What is Equivalent Kotlin code ? *

like image 456
Devrath Avatar asked Dec 22 '25 08:12

Devrath


1 Answers

In Kotlin, we do not necessarily need to put constants in a class, so these are valid in a Kotlin source file:

const val BASE_URL = "http://11.111.111.11:8000/"
const val TAXABLE_AMOUNT = 0.18
const val DAYS_INTERVAL_FOR_RATE_ME_DIALOG = 50000

If you want to keep the LinksAndKeys namespace, you could use:

object LinksAndKeys {
  const val BASE_URL = "http://11.111.111.11:8000/"
  const val TAXABLE_AMOUNT = 0.18
  const val DAYS_INTERVAL_FOR_RATE_ME_DIALOG = 50000  
}

You can then refer to values like LinksAndKeys.BASE_URL, either from Java or Kotlin.

like image 146
CommonsWare Avatar answered Dec 23 '25 23:12

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!