Kotlin learning (1): Understanding compile-time constants and read-only type variables and the difference between the two

1. Compile-time constants:

const val PI = 3.141592
  1. Compile-time constants can only be commonly used basic data types: (String, Double, Int, Float, Long, Short, Byte, Char, Boolean)
  2. Compile-time constants can only be defined outside the function (if they are defined within the function, the function assignment must be called at runtime, and they cannot be called compile-time constants, so compile-time constants can only be defined outside the function, so that initialized during compilation)

2. Read-only type variables

val PI = 3.141592
  1. Variables modified with val are read-only variables and cannot be modified.
  2. Generally, when defining variables, it is best to use val to modify them, and then choose var.

3. Kotlin’s excellent class deduction mechanism
When defining variables in Java, we often look like this

String name = "小郑"

And kotlin can do this:

var name : String = "小郑"

But due to Kotlin’s excellent class inference mechanism:
we can do this directly:

var name = "小郑"

4. There are no basic data types in Kotlin. Instead, all basic data types are encapsulated into a class. The advantage is that there are many more built-in functions that can be called.

Guess you like

Origin blog.csdn.net/XJ200012/article/details/122451234