This is the first time to try this writing style. If you think it works, give it a thumbs up. It’s important to me.




val

Val is used to declare the read-only variable.

This is the equivalent of a final modified variable in Java. This is easier to understand.

const

Const const compile-time Constants

A const constant must satisfy all three conditions:

  1. The value can only be: string and base type. 【String or a Primitive Type 】

  2. You can modify only global constants (top level), object members, and Companion members

  3. Const cannot modify a variable by itself. It must modify a variable with val.

    That is, const val must occur at the same time.

Const val is a compile-time constant whose value is known at compile time. You don’t need to rely on any variables created at run time.

The variable declared by val is read-only. You can only assign once, which can be at run time.

Compile-time constants are a special case of read-only variables.

The benefits of const

When referencing kotlin’s variables in Java code, you cannot use the variables of val directly, but you can use the variables of const val directly.

The following kotlin code:

Oh, now that’s interesting.

Compile-time constants without const modifications are not only not directly accessible in Java code, but also generate the corresponding getXXX() method.

This is very interesting, as constants: VAL_STRING, automatically generated methods: NormalClass.Com panion. GetVAL_STRING ().

Variables that use const val should not be used only with val, as this is less elegant and has lower compile performance than const val. Const val does not generate the corresponding getXXX() method.

Let’s see what’s going on here, okay?

Let’s see what NormalClass will compile to. Look at the corresponding Java code.

  • Kotlin code

    class NormalClass{
      companion object{
        const val CONST_VAL_STRING = "constValString"
        val VAL_STRING = "valString"}}Copy the code
  • Switch to Java code and see the truth

Other kotlin related blog highlights

  • Kotlin: How does Kotlin Solve Java Development Pain Points to Make Programmers Happier
  • Inside Kotlin: Why did Google choose Kotlin? How kotlin solves Java Development Pain points [continued]?
  • Go deep into kotlin: Go deep into kotin Any
  • In-depth Kotlin: One minute introduction to Kotiln coroutines, thread switching

The Nuggets are currently having their annual standings event, and deke is not sure how to get votes for the first time. Vote for me if you think I’m okay. link