官术网_书友最值得收藏!

Variables

In Kotlin, we have two types of variables: var and val. The first one, var, is a mutable reference (read-write) that can be updated after initialization. The var keyword is used to define a variable in Kotlin. It is equivalent to a normal (non-final) Java variable. If our variable needs to change at some point, we should declare it using the var keyword. Let's look at an example of a variable declaration:

    fun main(args: Array<String>) { 
        var fruit: String =  "orange" //1 
        fruit  = "banana" //2 
    } 
  1. Create a fruit variable and initialize it with the vale of the orange variable.
  2. Reinitialize the fruit variable with the value of the banana variable.

The second type of variable is a read-only reference. This type of variable cannot be reassigned after initialization.

The val keyword can contain a custom getter, so technically it can return different objects on each access. In other words, we can't guarantee that the reference to the underlying object is immutable:

val random: Int
get() = Random().nextInt()

Custom getters will be discussed in more detail in Chapter 4, Classes and Objects.

The val keyword is the equivalent of a Java variable with the final modifier. Using immutable variables is useful, because it makes sure that the variable will never be updated by mistake. The concept of immutability is also helpful for working with multiple threads without worrying about proper data synchronization. To declare immutable variables, we will use the val keyword:

    fun main(args: Array<String>) { 
        val fruit: String= "orange"http://1 
        fruit = "banana" //2  Error 
    } 
  1. Create the fruit variable and initialize it with the value of the orange string.
  2. The compiler will throw an error, because the fruit variable was already initialized.
Kotlin also allows us to define variables and functions at the level of the file. We will discuss this further in Chapter 3, Playing with Functions.

Notice that the type of the variable reference (var, val) relates to the reference itself, not the properties of the referenced object. This means that when using a read-only reference (val), we will not be able to change the reference that is pointing to a particular object instance (we will not be able to reassign variable values), but we will still be able to modify properties of referenced objects. Let's see it in action using an array:

    val list = mutableListOf("a","b","c") //1 
    list = mutableListOf("d", "e") //2 Error 
    list.remove("a") //3 
  1. Initialize a mutable list.
  2. The compiler will throw an error, because a value reference cannot be changed (reassigned).
  3. The compiler will allow us to modify the content of the list.

The val keyword cannot guarantee that the underlying object is immutable.

If we really want to make sure that the object will not be modified, we must use an immutable reference and an immutable object. Fortunately, Kotlin's standard library contains an immutable equivalent of any collection interface (List versus MutableList, Map versus MutableMap, and so on) and the same is true for helper functions that are used to create instances of a particular collection:

Variable/value definition

Reference can change

Object state can change

val = listOf(1,2,3)

No

No

val = mutableListOf(1,2,3)

No

Yes

var = listOf(1,2,3)

Yes

No

var = mutableListOf(1,2,3)

Yes

Yes

主站蜘蛛池模板: 栾城县| 色达县| 赣州市| 辽阳市| 乐业县| 和硕县| 四平市| 将乐县| 隆安县| 昆明市| 彝良县| 靖西县| 威远县| 威信县| 蕲春县| 阳西县| 德兴市| 龙胜| 安康市| 四川省| 湖南省| 福州市| 涞水县| 芒康县| 浠水县| 苗栗县| 南召县| 尼勒克县| 丰顺县| 顺平县| 镇康县| 盘山县| 镇沅| 河池市| 建昌县| 沙洋县| 景谷| 同江市| 保康县| 通江县| 长顺县|