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

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

    val

    Kotlin val keyword is for read-only properties in comparison with Kotlin var keyword. The other name for read-only property is immutable.

    Kotlin code:

    val variation: Long = 100L
    

    Java equivalent looks like this:

    final Long variation = 100L;
    


    const val

    We use const keyword for immutable properties too. const is used for properties that are known at compile-time. That's the difference. Take into consideration that const property must be declared globally.

    Kotlin code (in playground):

    const val WEBSITE_NAME: String = "Google"
    
    fun main() {    
        println(WEBSITE_NAME)
    }
    

    Java code (in playground):

    class Playground {
    
        final static String WEBSITE_NAME = "Google";
    
        public static void main(String[ ] args) {
            System.out.println(WEBSITE_NAME);
        }
    }
    
    0 讨论(0)
提交回复
热议问题