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

  • Functional Kotlin
  • Mario Arias Rivu Chakraborty
  • 358字
  • 2021-06-24 19:15:28

The difference between var and val

So, in order to encourage immutability but still let the developers have the choice, Kotlin introduced two types of variables. The first one is var, which is just a simple variable, just like in any imperative language. On the other hand, val brings us a bit closer to immutability; again, it doesn't guarantee immutability. So, what exactly does the val variable provide us? It enforces read-only, you cannot write into a val variable after initialization. So, if you use a val variable without a custom getter, you can achieve referential immutability.

Let's have a look; the following program will not compile:

fun main(args: Array<String>) { 
    val x:String = "Kotlin" 
    x+="Immutable"http://(1) 
} 

As I mentioned earlier, the preceding program will not compile; it will give an error on comment (1). As we've declared variable x as val, x will be read-only and once we initialize x; we cannot modify it afterwards.

So, now you're probably asking why we cannot guarantee immutability with val ? Let's inspect this with the following example:

object MutableVal { 
    var count = 0 
    val myString:String = "Mutable" 
        get() {//(1) 
            return "$field ${++count}"http://(2) 
        } 
} 
 
fun main(args: Array<String>) { 
    println("Calling 1st time ${MutableVal.myString}") 
    println("Calling 2nd time ${MutableVal.myString}") 
    println("Calling 3rd time ${MutableVal.myString}")//(3) 
} 

In this program, we declared myString as a val property, but implemented a custom get function, where we tweaked the value of myString before returning it. Have a look at the output first, then we will further look into the program:

As you can see, the myString property, despite being val, returned different values every time we accessed it. So, now, let us look into the code to understand such behavior.

On comment (1), we declared a custom getter for the val property myString. On comment (2), we pre-incremented the value of count and added it after the value of the field value, myString, and returned the same from the getter. So, whenever we requested the myString property, count got incremented and, on the next request, we got a different value. As a result, we broke the immutable behavior of a val property.

主站蜘蛛池模板: 洛宁县| 桃源县| 兰溪市| 静宁县| 濮阳县| 峨山| 忻城县| 庆云县| 织金县| 平陆县| 东安县| 禄劝| 阿鲁科尔沁旗| 巨鹿县| 石林| 刚察县| 深泽县| 将乐县| 江陵县| 元谋县| 乐东| 阿拉善盟| 喀喇沁旗| 溧水县| 图们市| 奉节县| 铁岭市| 长宁县| 永靖县| 于都县| 资源县| 崇礼县| 武夷山市| 丹阳市| 凌云县| 平原县| 凉城县| 江津市| 开原市| 花垣县| 衡水市|