Kotlin入门教程系列(二) 基本数据类型 Number

来源:互联网 发布:算法c语言实现pdf 网盘 编辑:程序博客网 时间:2024/05/29 14:14

Kotlin基本类型

Kotlin提供以下内置类型来表示数字 :

Double 64bit

Float 32bit

Long 64bit

Int 32bit

Short 16bit

Byte 8bit


这和Java是非常类似的,但是在kotlin中, character 不是 number,Kotlin中也没有八进制。

Long以L标识 123L,Float以f或者F标识 123.5F


可以用下划线让数字可读性更好 例如:


       val oneMillion = 1_000_000         val bytes = 0b11010010_01101001_10010100_10010010  

在Java中,数字都以它们的原始类型被物理存储在JVM中,除非我们需要null类型引用或者泛型(比如拆装箱这种 会包装一下)。

      val a: Int = 10000      print(a === a) // Prints 'true'      val boxedA: Int? = a      val anotherBoxedA: Int? = a      print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!  

( === 类似java中的比较地址)

val a: Int = 10000print(a == a) // Prints 'true'val boxedA: Int? = aval anotherBoxedA: Int? = aprint(boxedA == anotherBoxedA) // Prints 'true'  

(== 为值比较)


和Java不同的是 Kotlin的小数据类型并不会隐式的向上转换,比如

在 JAVA中 以下代码不会报错

    byte i = 1;    int k = i; //不会报错

但是 在Kotlin中 必须显式转换

    val b: Byte =1    val i: Int = b.toInt()

每一个Number数字类 都支持以下转换:

toByte()

toShort()

toInt()

toLong()

toFloat()

toDouble()

toChar()


隐式转换一般情况下是不容易被发觉的,因为我们使用了上下文推断出类型,并且算术运算会为合适的转换进行重载,比如

val l = 1L + 3 // Long + Int => Long  


版权所有 http://aiprogram.top 欢迎转载