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

前端 未结 7 2103
既然无缘
既然无缘 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:17

    In kotlin, const and val both represents the immutability and read only values and act as final keyword in java.

    val keyword must be used to declare for run time values and const keyword must be used to declare compile time values.

    Keep in mind, const must be used only with primitive data types not for function and constructors.

    Example -
    

    const val fun1 = anyFunctionOrConstructor() // it is not fine
        val fun2 = anyFunctionOrConstructor() // it is perfectly fine
        
        const val aa = "My String" // it is perfectly fine

提交回复
热议问题