The road to learning Kotlin (1): variables, constants, empty safety

1. var variables and common types

1.1 Variables and types

Kotlin's variable types are similar to Java's, but there are big differences in writing

        fun main() {
    
    
            var num:Int = 22
            println(num)
        }

The var reserved word is placed at the front to indicate that numit is a variable, and the data type is placed after the variable, separated by :, and there is no ;.
The variable type is similar to Java, providing Byte, Short, Int, Long, Float, Double,
Char, Boolean, and String As for the maximum and minimum values ​​of each type, you can use each data type (except Boolean and String) MAX_VALUEand MIN_VALUEto get it.

1.2 Intelligent inference

If the above code has a warning Explicitly given type is redundant here on AndroidStudio , the IDE warns that "the explicitly given type is redundant here", and the IDE can deduce the specific type through intelligent inference.
The following code compiles and passes:

        fun main() {
    
    
            var num = 22
            num = 2
            println(num)
        }

The above code number is changed to 33.4, "aaaa", all of which can be compiled, thanks to intelligent inference. However, there is a point worth noting here. After the variable is initialized, it will report an error if it is reassigned to other types of values. For example, the following code:

        fun main() {
    
    
            var num = 2
            num = 223.44 // 报错
        }

2. Constants

2.1 val constants

After val is modified, it cannot be assigned again after it is initialized once.

        fun main() {
    
    
            val num = 2
            num =23 // 编译报错
        }

After the val constant is initialized once, it cannot be assigned again.

2.2 const constants

The const keyword is unique to kotlin, and there is no such keyword in java.
const must be used with val, and can only be used in companion objectand objectTop-level (top-level declaration).

const val num = 2

companion object {
    
    
	const val num = 2
}

object Test{
    
    
    const val num = 2
}

3. The difference between var variable, val constant and const

If you need to understand the problem, the best way is to decompile it into Java code
kotlin code:

class Main {
    
    

    var variable = 2

    val constant = 2

    companion object{
    
    

        const val constVal = 2

        @JvmStatic
        fun main(args:Array<String>){
    
    

        }
    }
}

Java code after decompilation:

	// 代码省略...
	private int variable = 2; // var
    private final int constant = 2; // val
    public static final int constVal = 2; // const val

The difference can be clearly seen through the decompiled code above.
For more details about var val const compilation, you can read this article:
kotlin var, val, const val modifier compilation

4. Air safety

4.1 ? and!!

?Nullable types only need to be added after the type

		fun main(){
    
    
			// 可空类型
			// 这时候由String类型改为String?类型
			var str:String? = "aaa"
            println(str?.length) // 可空类型的调用
        }

The role of the nullable type is to solve the null pointer exception at the compilation stage, and str?.lengththis way of writing can guarantee thread safety .
The following is the comparison code:

        fun main(){
    
    
            // 第一种
            var str0:String = null // 直接编译出错
            println(str0.length)
			
			// 第二种,编译和运行正常
			var str0:String? = null // String类型改为String?类型
    		println(str0?.length) // 不会调用length,打印null
        }

If you want kotlin code to throw an exception when it encounters a null pointer, you can use!!

        fun main(){
    
    
            var str:String? = "aaa"
            println(str!!.length) // 如果str为null,这里会抛异常
        }

4.2 ?:

?There may be some unexpected problems when using it, such as the following code:

        fun main(){
    
    
            var num:Int? = 2
            if (num > 0){
    
    // 编译失败
                println("小于0")
            }
        }

As shown in the above code, this situation cannot be compiled, so how to solve this problem? This can ?:be used to solve.

        fun main(){
    
    
            var num:Int? = 2
            if (num?:-1 > 0){
    
    
                println("小于0")
            }
        }

变量0?:变量1The role, if 变量0it is null, then take 变量1the value. The value to take if 变量0not null 变量0.

Four. Summary

The above content is about kotlin's val, var, const val,?,!!, and the usage and summary of variable types.

Guess you like

Origin blog.csdn.net/RQ997832/article/details/122710233