Language design question: What is the reason for `...
# announcements
m
Language design question: What is the reason for
const
keyword existing? Why can't compiler automatically treat all vals that are assigned to constant value (such as string literal or number literal) as
const
? Is there a situation where using
const
is not preferred?
d
const
will be inlined by the compiler at the site where it is used. If you change the value, all users of your library will have to recompile
m
oh, I see
so it is primarily for library authors?
🚫 1
t
No,
const val
is just like
static final
primitives in Java, it defines a constant that can be referenced elsewhere, so that you don't have to change all usage of the same
String
or
Int
litteral in your whole code when its value change. The fact that the compiler inlines the value in the bytecode is just an optimization, but an actual field is created for the constant too so that libraries can use it if it is public.
👍 1
d
the library will still inline it.
w
To be honest, I ever used
const
in the app as well. now that you spoke about it, I have a go with the decompiler, and looks weird...
Copy code
class PathTest1 {
    companion object {
        private const val NAME = "This is a name!"
    }

    private fun asas1() {
        println(NAME)
    }

    private fun asas2() {
        println(NAME)
    }
}
It decompiles to:
Copy code
public final class PathTest1 {
   private static final String NAME = "This is a name!";
   public static final PathTest1.Companion Companion = new PathTest1.Companion((DefaultConstructorMarker)null);

   private final void asas1() {
      String var1 = "This is a name!";
      System.out.println(var1);
   }

   private final void asas2() {
      String var1 = "This is a name!";
      System.out.println(var1);
   }

   public static final class Companion {
      private Companion() {
      }

      public Companion(DefaultConstructorMarker $constructor_marker) {
         this();
      }
   }
}
And like this:
Copy code
class PathTest2 {
    private val NAME = "This is a name!"

    private fun asas1() {
        println(NAME)
    }

    private fun asas2() {
        println(NAME)
    }
}
It decompiles to:
Copy code
public final class PathTest2 {
   private final String NAME = "This is a name!";

   private final void asas1() {
      String var1 = this.NAME;
      System.out.println(var1);
   }

   private final void asas2() {
      String var1 = this.NAME;
      System.out.println(var1);
   }
}
d
const
makes this behavior of the Java compiler a choice.
In java this will just happen transparently, without choice by the author.