在Kotlin中,一切皆是对象。
1. 数字类型
Kotlin处理数字跟Java很相似,但不完全相同,比如在Kotlin中数字不能隐式转换。
Kotlin提供了以下内置几种数字类型(与Java相似)
类型 | Bit width |
---|---|
Double | 64 |
Float | 32 |
Long | 64 |
Int | 32 |
Short | 16 |
Byte | 8 |
注意:在Kotlin中字符不是数字
-
数字表示
整型数:123
长整型数:123L
十六进制:0x0F
二进制数:0b00001011
注意:不支持八进制数表示。
双精度浮点数:123.5, 123.5e10
单精度浮点数:123.5f,123.5F
-
数字中的下划线(1.1版本开始支持)
可以在数字中使用下划线使得数字更具有可读性;
val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010
Representation
在Java平台上,数字作为JVM的初始类型进行物理存储,除非我门需要一个可空数字引用(例如Int?)或涉及泛型,在后一种情况中,数字会被包装。
On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int?) or generics are involved. In the latter cases numbers are boxed.
Note that boxing of numbers does not necessarily preserve identity:
val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
On the other hand, it preserves equality:
val a: Int = 10000
print(a == a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA == anotherBoxedA) // Prints 'true'
-
明确转换
Due to different representations, smaller types are not subtypes of bigger ones. If they were, we would have troubles of the following sort:
// Hypothetical code, does not actually compile:
val a: Int? = 1 // A boxed Int (java.lang.Integer)
val b: Long? = a // implicit conversion yields a boxed Long (java.lang.Long)
print(a == b) // Surprise! This prints "false" as Long's equals() check for other part to be Long as well
较小的类型不会被隐式转换为更大的类型,这就意味着我们不能在没有显示转换的情况下将Byte类型的值赋值给Int类型的变量。
val b: Byte = 1 // OK, literals are checked statically
val i: Int = b // ERROR
我门可以使用显示的转换来扩大数字
val i: Int = b.toInt() // OK: explicitly widened
每种数字类型都支持以下转换方法:
toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
toChar(): Char
Kotlin可以根据上下文推断类型,比如:
val l = 1L + 3 // Long + Int => Long