Variables in Kotlin, differences with Java: 'var' vs. 'val'?

前端 未结 4 874
失恋的感觉
失恋的感觉 2021-02-05 11:21

I am trying to learn Kotlin. What is val, var and internal in Kotlin compared to Java?

In Java:

 RadioGroup radio         


        
相关标签:
4条回答
  • 2021-02-05 11:54

    In kotlin we can declare variable in two types: val and var. val cannot be reassigned, it works as a final variable.

    val x = 2
    x=3 // cannot be reassigned
    

    On the other side, var can be reassigned it is mutable

    var x = 2
    x=3 // can be reassigned
    
    0 讨论(0)
  • 2021-02-05 12:06

    val and var are the two keywords you can use to declare variables (and properties). The difference is that using val gives you a read-only variable, which is the same as using the final keyword in Java.

    var x = 10    // int x = 10;
    val y = 25    // final int y = 25;
    

    Using val whenever you can is the convention in Kotlin, and you should only make something a var if you know that you'll be changing its value somewhere.

    See the official documentation about defining local variables and declaring properties.


    internal is a visibility modifier that doesn't exist in Java. It marks a member of a class that will only be visible within the module it's in. This is a similar visibility to what the default package visibility gives you in Java (which is why the converter would use it when converting members with package visibility). However, it's not exactly the same. Also, note that it's not the default visibility in Kotlin, classes and their members in Kotlin are public by default.

    There is more in the documentation about visiblity modifiers.

    0 讨论(0)
  • 2021-02-05 12:17

    val use to declare final variable. Characteristics of val variables

    1. Must be initialized
    2. value can not be changed or reassign

    var is as a general variable

    1. We can initialize later by using lateinit modifier

      [lateinit also use for global variable we can not use it for local variable]

    2. value can be changed or reassign but not in global scope

    val in kotlin is like final keyword in java

    0 讨论(0)
  • 2021-02-05 12:21

    val : immutable data variable

    var : mutable data variable

    When you converted your Java code to Kotlin:

    1. A converter found that you have not initialised variables, so it made them var(mutable) as you will initialise them later.

    2. Probably your variables are unused, so the converter made them internal, guessing you will not use them outside of your package.

    For more information on var and var read this, and for internal read this.

    0 讨论(0)
提交回复
热议问题