在Kotlin中爱谁,一切皆是對(duì)象合砂。
1. 數(shù)字類型
Kotlin處理數(shù)字跟Java很相似脓规,但不完全相同,比如在Kotlin中數(shù)字不能隱式轉(zhuǎn)換饿幅。
Kotlin提供了以下內(nèi)置幾種數(shù)字類型(與Java相似)
類型 | Bit width |
---|---|
Double | 64 |
Float | 32 |
Long | 64 |
Int | 32 |
Short | 16 |
Byte | 8 |
注意:在Kotlin中字符不是數(shù)字
-
數(shù)字表示
整型數(shù):123
長(zhǎng)整型數(shù):123L
十六進(jìn)制:0x0F
二進(jìn)制數(shù):0b00001011
注意:不支持八進(jìn)制數(shù)表示凡辱。
雙精度浮點(diǎn)數(shù):123.5, 123.5e10
單精度浮點(diǎn)數(shù):123.5f,123.5F
-
數(shù)字中的下劃線(1.1版本開(kāi)始支持)
可以在數(shù)字中使用下劃線使得數(shù)字更具有可讀性栗恩;
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平臺(tái)上透乾,數(shù)字作為JVM的初始類型進(jìn)行物理存儲(chǔ),除非我門需要一個(gè)可空數(shù)字引用(例如Int?)或涉及泛型磕秤,在后一種情況中续徽,數(shù)字會(huì)被包裝。
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'
-
明確轉(zhuǎn)換
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
較小的類型不會(huì)被隱式轉(zhuǎn)換為更大的類型亲澡,這就意味著我們不能在沒(méi)有顯示轉(zhuǎn)換的情況下將Byte類型的值賦值給Int類型的變量钦扭。
val b: Byte = 1 // OK, literals are checked statically
val i: Int = b // ERROR
我門可以使用顯示的轉(zhuǎn)換來(lái)擴(kuò)大數(shù)字
val i: Int = b.toInt() // OK: explicitly widened
每種數(shù)字類型都支持以下轉(zhuǎn)換方法:
toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
toChar(): Char
Kotlin可以根據(jù)上下文推斷類型,比如:
val l = 1L + 3 // Long + Int => Long