Numbers
https://kotlinlang.org/docs/basic-types.html#numbers
Interger Types
| Type | Size(bits) | Min value | Max value |
|---|---|---|---|
| Byte | 8 | -128 | 127 |
| UByte | 8 | 0 | 255 |
| Short | 16 | -32768 | 32767 |
| UShort | 16 | 0 | 65535 |
| Int | 32 | -2,147,483,648(-231) | 2,147,483,647(231 - 1) |
| UInt | 32 | 0 | 232 - 1 |
| ULong | 64 | 0 | 264 - 1 |
val one = 1 // Int val threeBillion = 3000000000 // Long val oneLong = 1L // Long val oneByte: Byte = 1 val b: UByte = 1u val s: UShort = 1u val l: ULong = 1u val a1 = 42u // UInt: no expected type provided, constant fits in UInt val a2 = 0xFFFF_FFFF_FFFFu // ULong: no expected type provided, constant doesn't fit in UInt val a = 1UL // ULong, even though no expected type provided and constant fits into UInt浮点型
Floating-point types
| Type | Size(bits) | Significant bits | exponent bits | Decimal digits |
|---|---|---|---|---|
| Float | 32 | -24 | 8 | 6-7 |
| Double | 64 | -53 | 11 | 15-16 |
val pi = 3.14 // Double // val one: Double = 1 // Error: type mismatch val oneDouble = 1.0 // Double
尾部用 f 或 F 表示单精度浮点型
val e = 2.7182818284 // Double val eFloat = 2.7182818284f // Float, actual value is 2.7182817
Kotlin中没有隐式转换:
For example, a function with a Double parameter can be called only on Double values, but not Float, Int, or other numeric values.
例如:
fun main() {
fun printDouble(d: Double) { print(d) }
val i = 1
val d = 1.0
val f = 1.0f
printDouble(d)
// printDouble(i) // Error: Type mismatch
// printDouble(f) // Error: Type mismatch
}
数字表示方法
- 十进制数,Decimals: 123
- 长整型十进制数,Longs are tagged by a capital L: 123L
- 十六进制数,Hexadecimals: 0x0F
- 二进制数,Binaries: 0b00001011
- 双精度浮点型,Doubles by default: 123.5, 123.5e10
- 单精度浮点型,Floats are tagged by f or F: 123.5f
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数据类型转换
不同类型的数据做相等比较会报错
val a = 1 val b = 2L println(a==b)
// 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(b == a) // Surprise! This prints "false" as Long's equals() checks whether the other is Long as well
Int? :表示可空类型,就是一种特殊的值类型,它的值可以为 null
用于给变量设初值得时候,给变量(Int类型)赋值为 null,而不是0
运行报错:
Operator ‘==’ cannot be applied to ‘Int’ and ‘Long’
计算过程中隐式转换:
val l = 1L + 3 // Long + Int => Long
- toByte(): Byte
- toShort(): Short
- toInt(): Int
- toLong(): Long
- toFloat(): Float
- toDouble(): Double
- toChar(): Char
JVM平台
On the JVM platform, numbers are stored as primitive types: int, double, and so on. Exceptions are cases when you create a nullable number reference such as Int? or use generics. In these cases numbers are boxed in Java classes Integer, Double, and so on.
val a: Int = 100 val boxedA: Int? = a val anotherBoxedA: Int? = a val b: Int = 10000 val boxedB: Int? = b val anotherBoxedB: Int? = b println(boxedA === anotherBoxedA) // true println(boxedB === anotherBoxedB) // false
断点debug看内存地址:
因为在JVM平台中,对于 -128 到 127 范围内的整型做了内存优化,他们都指向同一地址:
All nullable references to a are actually the same object because of the memory optimization that JVM applies to Integers between -128 and 127. It doesn’t apply to the b references, so they are different objects.
val b: Int = 10000 println(b == b) // Prints 'true' val boxedB: Int? = b val anotherBoxedB: Int? = b println(boxedB == anotherBoxedB) // Prints 'true'整数除法
val x = 5L / 2 // 整数除法,小数部分直接截断 println(x == 2L) // 直接截断为2L
true
val x = 5 / 2.toDouble() println(x == 2.5)
位操作true
Bitwise operations
仅作用于 Int 和 Long 类型
They can be applied only to Int and Long
- shl(bits) – signed shift left,有符号左移
- shr(bits) – signed shift right,有符号右移
- ushr(bits) – unsigned shift right,无符号右移
- and(bits) – bitwise and,按位与
- or(bits) – bitwise or,按位或
- xor(bits) – bitwise xor,按位异或
- inv() – bitwise inversion,按位翻转
- || - 逻辑 OR
- &&- 逻辑 AND
- !- 逻辑 NOT
val myTrue: Boolean = true val myFalse: Boolean = false println(myTrue || myFalse) // true println(myTrue && myFalse) // false println(!myTrue) // false字符型 (Char)
字符型用单引号表示 '1'
转义字符:t b n r ' " \ $
字符转为整数:
'1'.digitToInt()
字符串 (Strings)Returns the numeric value of the decimal digit that this Char represents. Throws an exception if this Char is not a valid decimal digit.
val str = "abcd 123"
val str2 = "abcd 123"
println(str[0])
println(str[1])
for (c in str) {
println(c)
}
a
b
a
b
c
d
1
2
3
字符串不可变,相同的字符串具有相同的地址
字符串换行:
val text = """
for (c in "foo")
print( c )
"""
for (c in “foo”)
print( c )
val withoutMargin1 = """ABC
|123
|456""".trimMargin()
println(withoutMargin1) // ABCn123n456
val withoutMargin2 = """
#XYZ
#foo
#bar
""".trimMargin("#")
println(withoutMargin2) // XYZnfoonbar
Tell me and I forget.
Teach me and I remember.
Involve me and I learn.
(Benjamin Franklin)
By default, | is used as margin prefix, but you can choose another character and pass it as a parameter, like trimMargin(“>”),默认删掉每行首、尾字符 |
fun String.trimMargin(marginPrefix: String = "|"): String字符串模板 println() 中应用最多
A template expression starts with a dollar sign ($) and consists of either a name:
val i = 10
println("i = $i") // prints "i = 10"
i = 10
花括号内进行计算
val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"
abc.length is 3
要在字符串中使用美元符号
val price = """
${'$'}_9.99
"""
Array
class Arrayprivate constructor() { val size: Int operator fun get(index: Int): T operator fun set(index: Int, value: T): Unit operator fun iterator(): Iterator // ... }
// Creates an Arraywith values ["0", "1", "4", "9", "16"] val asc = Array(5) { i -> (i * i).toString() } asc.forEach { println(it) }
0
1
4
9
16
[] operation stands for calls to member functions get() and set()
Primitive type arraysByteArray, ShortArray, IntArray
这些 Array 与 Array 没有继承关系
val x: IntArray = intArrayOf(1, 2, 3)
x[0] = x[1] + x[2]
// Array of int of size 5 with values [0, 0, 0, 0, 0]
val arr = IntArray(5)
// e.g. initialise the values in the array with a constant
// Array of int of size 5 with values [42, 42, 42, 42, 42]
val arr = IntArray(5) { 42 }
// e.g. initialise the values in the array using a lambda
// Array of int of size 5 with values [0, 1, 2, 3, 4]
// (values initialised to their index value)
var arr = IntArray(5) { it * 1 }



