Kotlin Learning - Variables

variable declaration

There are two keywords for Kotlin variables, namely valand var. In general, varkeywords define variables and valkeywords define constants.

val keyword

valImmutable variables, corresponding to java finalvariables, can only be assigned once and cannot be reassigned.

val str1 = "hello world!"

Compile to Java code:

@NotNull
private final String str1 = "hello world!";

var keyword

varfinalVariable variables, corresponding to non- variables in java , can be assigned repeatedly.

fun main() {
    
    
    var str2 = "kotlin"
    //可以再次赋值
    str2 = "hello"
}

Compile to Java code:

@NotNull
private String str2 = "kotlin";

Type inference in Kotlin

When the above two variables are declared, the variable type is not declared. This is because Kotlin has a type deduction mechanism, and str1 and str2 will be deduced as String types by default according to the assignment. If you assign an Int type again, an error will be reported, the code is as follows:

fun main() {
    
    
    var str2 = "kotlin"
    //报错
    str2 = 1
}

Of course, the type of the variable can also be indicated explicitly.

fun main() {
    
    
    var str2: String
    var num: Int
}

basic type

Primitive types no longer exist in Kotlin, object types will all be used.

Java basic types Kotlin object type Object Type Description
int Int integer
long Long long integer
short Short short integer
float Float single precision floating point
double Double double precision floating point
boolean Boolean Boolean
char Char character type
byte Byte Byte

number type

Number type: byte,short,int,long,float,double. Like Java, all numeric types in Kotlin are signed, which means they can represent both positive and negative numbers.

1. Digital security transformation:

fun main() {
    
    
	val num1: Int = "9.8".toInt()
}

Executing the above function directly will report an error: NumberFormatException, let's modify it:

fun main() {
    
    	
    val num2: Int? = "9.8".toIntOrNull()
    println(num2)
}
//运行结果是:null

You can use the safe conversion function toIntOrNull when doing the conversion, and return if the value cannot be converted correctly null.

2. Double to Int and type formatting

fun main() {
    
    
	//转化丢失精度
    println(8.956756.toInt())
    //四舍五入
    println(8.956756.roundToInt())
    println(8.156756.roundToInt())
    //格式化:只需要小数点后两位
    val s:String = "%.2f".format(8.956756)
    println(s)
}

//运行结果:
8
9
8
8.96

Guess you like

Origin blog.csdn.net/kongqwesd12/article/details/130964197