Vignesh Prabhu

Vignesh Prabhu

Kotlin basics - const vs val

Kotlin basics - const vs val

Lets first understand basics of val and const

val

  • read only
  • known at runtime

const

  • read only
  • known at compile time
  • can only take String or primitive data types
  • no custom getter methods
  • place to declare

1.top level declaration in a file

2.object file declaration

3.companion object declaration

Now lets write a small kotlin code to understand val and const .The following code does the following

1.takes the place holder in const

2.dynamic values in val which includes function

const declaration

const val START_TEXT = "My Name is"
const val MIDDLE_TEXT = "and I am"
const val END_TEXT = "years old"

val declaration for place holder text

val myName= "Ajay"
val myAge = 27

val runtime declaration

fun getFinalText()  = "$START_TEXT $myName $MIDDLE_TEXT $myAge $END_TEXT"
val output = getFinalText()

Complete kotlin code

val myName= "Ajay"
val myAge = 27

const val START_TEXT = "My Name is "
const val MIDDLE_TEXT = " and I am "
const val END_TEXT = " years old"

fun getFinalText()  = "$START_TEXT$myName$MIDDLE_TEXT$myAge$END_TEXT"
val output = getFinalText()

fun main() {
    println(output)
}

const compile time error when assigning runtime value

Screenshot 2021-04-26 at 2.59.25 PM.png

Java compile code for above kotlin code

public final class ConstvsValKt {
   @NotNull
   private static final String myName = "Ajay";
   private static final int myAge = 27;
   @NotNull
   public static final String START_TEXT = "My Name is";
   @NotNull
   public static final String MIDDLE_TEXT = "and I am";
   @NotNull
   public static final String END_TEXT = "years old";
   @NotNull
   private static final String output = getFinalText();

   @NotNull
   public static final String getMyName() {
      return myName;
   }

   public static final int getMyAge() {
      return myAge;
   }

   @NotNull
   public static final String getFinalText() {
      return "My Name is " + myName + " and I am " + myAge + " years old";
   }

   @NotNull
   public static final String getOutput() {
      return output;
   }

   public static final void main() {
      String var0 = output;
      boolean var1 = false;
      System.out.println(var0);
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }
}

So finally , I hope i made somebody understand const and val .

Please leave your comments to improve.

Enjoy coding , untill next time

 
Share this