The difference between variables var and val in Android Kotlin syntax





var (variable variable)

Used to declare a variable, indicating that the variable can be modified, reassigned, and referenced;
var is a mutable variable, which is a variable that can be changed to another value by reassignment;
this way of declaring variables Same way as declaring variables in Java.



grammar

Define variables: Variables are readable and writable, and can be assigned repeatedly after definition, which is equivalent to ordinary variables in Java:

var <variable identifier>: <data type> = <initialization value>


var name: String = "kotlin"	//声明时直接赋值
var age: Int 	 //无初始化值时不能省略数据类型
age = 100		//先声明后赋值
var sex = 1		//自动推断数据类型 Int
 


  • For variable variables, you should generally pay attention to using the safe operator?, and you must add it when using it.
    For example: var name: String? = null






val (value) :

It is used to declare a constant, indicating that the variable cannot be modified once it is assigned, and the reference is immutable;
val is a read-only variable, and this way of declaring a variable is equivalent to a Final variable in Java;
a val must be initialized when it is created, because later cannot be changed.



grammar

Define constants: Constants are readable but not writable. Once defined, their values ​​cannot be modified, which is equivalent to final-modified constants in Java

val <constant identifier>: <data type> = <initialization value>


val PI: Double = 3.1415 //声明常量直接赋值
// PI = 3.20 此时会报语法错误,val修饰的常量不能重新赋值
val title: String		//声明常量,暂不赋值
title = "kotlin Hello"	//未赋值的常量可以赋值一次
 



  • An important concept: use val whenever possible, because val variables are more safe and reliable in complex logic.









Summarize

Guyu














Note:
Likes, comments, and reprints are welcome. Please give the link to the original text in an obvious place on the article page
. Those who know, thank you for reading my article in the vast crowd.
Where is the signature without personality!
For details, please follow me
and continue to update

Scan to have a surprise!
© 2022 09 - Guyu.com | [Copyright infringement must be investigated]

Guess you like

Origin blog.csdn.net/weixin_49770443/article/details/126945989