What is the difference between “const” and “val”?

前端 未结 7 2105
既然无缘
既然无缘 2020-12-22 17:20

I have recently read about the const keyword, and I\'m so confused! I can\'t find any difference between const and the val keyword, I

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 18:15

    const kotlin to Java

    const val Car_1 = "BUGATTI" // final static String Car_1 = "BUGATTI";
    

    val kotlin to Java

    val Car_1 = "BUGATTI"   // final String Car_1 = "BUGATTI";
    

    In simple Language

    1. The value of the const variable is known at compile time.
    2. The value of val is used to define constants at run time.

    Example 1-

    const val Car_1 = "BUGATTI" ✔  
    val Car_2 = getCar() ✔    
    const val Car_3 = getCar() ❌ 
    
    //Because the function will not get executed at the compile time so it will through error
    
    fun getCar(): String {
        return "BUGATTI"
    }
    

    This is because getCar() is evaluated at run time and assigns the value to Car.

    Additionally -

    1. val is read-only means immutable that is known at run-time
    2. var is mutable that is known at run-time
    3. const are immutable and variables that are known at compile-time

提交回复
热议问题