---
title: 基本类型
description: 数值、布尔、字符、字符串、数组，以及 List、Map、Set。
date: 2025-04-28
navigation:
  icon: i-simple-icons-kotlin
seo:
  title: Kotlin 基本类型
  description: Int 到 Double 的范围和转换，布尔、字符、字符串模板，还有数组和集合。
links:
  - label: 基本语法
    icon: i-simple-icons-kotlin
    to: /kotlin/basic-syntax
  - label: 控制流程
    icon: i-simple-icons-kotlin
    to: /kotlin/control-flow
categories:
  - kotlin
tags:
  - Kotlin
---

## 数值类型

在`Kotlin`中，一切都是对象，因为你可以调用任何变量的成员函数和属性。某些类型可以具有特殊的内部表现形式，例如，数字、字符和布尔值可以在运行时表示为原始值 - 但对于用户来说，它们看起来就像普通的类。

::tip
对比`Java`中的数据类型，其中`int`对应了`Int`，看上去只是首字母变大写，因为在`Kotlin`中一切都是对象。
::


### 整数类型

`Kotlin` 提供了一组表示数字的内置类型。 对于整数，有四种不同大小的类型，因此值的范围也不同：

| 类型  | 大小（比特数） |                最小值                |                最大值                |
| :---: | :------------: | :----------------------------------: | :----------------------------------: |
| Byte  |       8        |                 -128                 |                 127                  |
| Short |       16       |                -32768                |                32767                 |
|  Int  |       32       |            -2,147,483,648（−2³¹）            |            2,147,483,647（2³¹−1）            |
| Long  |       64       | -9,223,372,036,854,775,808（−2⁶³） | 9,223,372,036,854,775,807（2⁶³−1） |

当初始化一个没有显式指定类型的变量时，编译器会自动推断为足以表示该值的最小类型。 如果不超过 `Int` 的表示范围，那么类型是 `Int`。 如果超过了， 那么类型是 `Long`。 如需显式指定 `Long` 值，请给该值追加后缀 `L`。 显式指定类型会触发编译器检测该值是否超出指定类型的表示范围。

```kotlin
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1
```

::tip
除了整数类型之外，`Kotlin`还提供无符号整数类型。
::


::accordion
---
class: "my-5 rounded-md border border-primary/25 bg-primary/10 px-4"
ui:
  item: "border-b-0"
  trigger: "py-3 text-base font-semibold text-primary"
  leadingIcon: "text-primary"
  trailingIcon: "text-primary"
---

:::accordion-item{label="Int 的部分源码" icon="i-lucide-book-open" class="!text-default"}
还记得吗，`Kotlin` 中一切都是对象，在项目里点进去可以看到这部分源码。

```kotlin
/**
 * Represents a 32-bit signed integer.
 * On the JVM, non-nullable values of this type are represented as values of the primitive type `int`.
 */
public class Int private constructor() : Number(), Comparable<Int> {
    companion object {
        /**
         * A constant holding the minimum value an instance of Int can have.
         */
        public const val MIN_VALUE: Int = -2147483648

        /**
         * A constant holding the maximum value an instance of Int can have.
         */
        public const val MAX_VALUE: Int = 2147483647

        /**
         * The number of bytes used to represent an instance of Int in a binary form.
         */
        @SinceKotlin("1.3")
        public const val SIZE_BYTES: Int = 4

        /**
         * The number of bits used to represent an instance of Int in a binary form.
         */
        @SinceKotlin("1.3")
        public const val SIZE_BITS: Int = 32
    }
        /**
     * Compares this value with the specified value for order.
     * Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
     * or a positive number if it's greater than other.
     */
    @kotlin.internal.IntrinsicConstEvaluation
    public operator fun compareTo(other: Double): Int

    /** Adds the other value to this value. */
    @kotlin.internal.IntrinsicConstEvaluation
    public operator fun plus(other: Byte): Int
   ///......
}
```

:::
::


可以看到大部分内置函数，好比一个`Int`的值去进行加法，其实就等同于调用了`Int.plus(value)`方法;

### 浮点类型

对于实数，`Kotlin` 提供了浮点类型`Float`与`Double`类型，遵循[`IEEE 754`](https://zh.wikipedia.org/wiki/IEEE_754) 标准。 `Float`表达 `IEEE 754`单精度，而`Double`表达双精度。

|   类型   | 大小（比特数） | 有效数字比特数 | 指数比特数 | 十进制 |
| :------: | :------------: | :------------: | :--------: | :----: |
| `Float`  |       32       |       24       |     8      |  6-7   |
| `Double` |       64       |       53       |     11     | 15-16  |

可以使用带小数部分的数字初始化` Double` 与 `Float` 变量。 小数部分与整数部分之间用句点（`.`）分隔 对于以小数初始化的变量，编译器会推断为 `Double` 类型：

```kotlin
val pi = 3.14 // Double
// val one: Double = 1 // 错误：类型不匹配
val oneDouble = 1.0 // Double
```

如需将一个值显式指定为 `Float` 类型，请添加 `f` 或 `F` 后缀。 如果这样的值包含多于 `6～7` 位十进制数，那么会将其舍入：

```kotlin
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float，实际值为 2.7182817
```

与一些其他语言不同，`Kotlin` 中的数字没有隐式拓宽转换。 例如，具有 `Double` 参数的函数只能对 `Double`值调用，而不能对 `Float`、 `Int` 或者其他数字值调用：

```kotlin
fun main() {
    fun printDouble(d: Double) { print(d) }

    val i = 1
    val d = 1.0
    val f = 1.0f

    printDouble(d)
//    printDouble(i) // 错误：类型不匹配
//    printDouble(f) // 错误：类型不匹配
}
```

### `JVM` 平台的数字表示

在 `JVM` 平台数字存储为原生类型 `int`、 `double` 等。 例外情况是当创建可空数字引用如 `Int?` 或者使用泛型时。 在这些场景中，数字会装箱为 `Java` 类 `Integer`、 `Double` 等。

对相同数字的可为空引用可能会引用不同的对象：

```kotlin
fun main() {
//sampleStart
    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
//sampleEnd
}
```

由于 `JVM` 对 `-128` 到 `127` 的整数（`Integer`）应用了内存优化，因此，`a` 的所有可空引用实际上都是同一对象。但是没有对 `b` 应用内存优化，所以它们是不同对象。

另一方面，它们仍然相等:

```kotlin
fun main() {
//sampleStart
    val b: Int = 10000
    println(b == b) // 输出“true”
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b
    println(boxedB == anotherBoxedB) // 输出“true”
//sampleEnd
}
```

### 显式数字转换

由于不同的表示方式，较小类型并不是较大类型的子类型。 如果它们是的话，就会出现下述问题：

```kotlin
// 假想的代码，实际上并不能编译(错误代码)：
val a: Int? = 1 // 一个装箱的 Int (java.lang.Integer)
val b: Long? = a // 隐式转换产生一个装箱的 Long (java.lang.Long)
print(b == a) // 惊！这将输出“false”鉴于 Long 的 equals() 会检测另一个是否也为 Long
```

上面情况一旦允许会有很大的安全问题

因此较小的类型不能 隐式转换为较大的类型。 这意味着把 `Byte` 型值赋给一个 `Int` 变量必须显式转换：

```kotlin
fun main() {
//sampleStart
    val b: Byte = 1 // OK, 字面值会静态检测
    // val i: Int = b // 错误
    val i1: Int = b.toInt()
//sampleEnd
}
```

所有数字类型都支持转换为其他类型：

- `toByte()`: `Byte`
- `toShort()`: `Short`
- `toInt()`: `Int`
- `toLong()`: `Long`
- `toFloat()`: `Float`
- `toDouble()`: `Double`

有些情况都不需要显式类型转换，因为类型会从上下文推断出来， 而算术运算会有重载做适当转换，例如：

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

### 数字运算

`Kotlin`支持数字运算的标准集：`+`、 `-`、 `*`、 `/`、 `%`。它们已定义为相应的类成员：

```kotlin
fun main() {
//sampleStart
    println(1 + 2)
    println(2_500_000_000L - 1L)
    println(3.14 * 2.71)
    println(10.0 / 3)
//sampleEnd
}
```

#### 整数除法

整数间的除法总是返回整数。会丢弃任何小数部分。

```kotlin
fun main() {
//sampleStart
    val x = 5 / 2
    //println(x == 2.5) // ERROR: Operator '==' cannot be applied to 'Int' and 'Double'
    println(x == 2)
//sampleEnd
}
```

对于任何两个整数类型之间的除法来说都是如此：

```kotlin
fun main() {
//sampleStart
    val x = 5L / 2
    println(x == 2L)
//sampleEnd
}
```

如需返回浮点类型，请将其中的一个参数显式转换为浮点类型：

```kotlin
fun main() {
//sampleStart
    val x = 5 / 2.toDouble()
    println(x == 2.5)
//sampleEnd
}
```

### 位运算

`Kotlin` 对整数提供了一组位运算。它们直接使用数字的比特表示在二进制级别进行操作。 位运算有可以通过中缀形式调用的函数表示。只能应用于 `Int` 与 `Long`：

```kotlin
val x = (1 shl 2) and 0x000FF000
```

这是完整的位运算列表：

- `shl(bits)` – 有符号左移
- `shr(bits)` – 有符号右移
- `ushr(bits)` – 无符号右移
- `and(bits)` – 位与
- `or(bits)` – 位或
- `xor(bits)` – 位异或
- `inv()` – 位非

### 浮点数比较

本节讨论的浮点数操作如下：

- 相等性检测：`a == b` 与 `a != b`
- 比较操作符：`a < b`、 `a > b`、 `a <= b`、 `a >= b`
- 区间实例以及区间检测：`a..b`、 `x in a..b`、 `x !in a..b`

当其中的操作数 `a` 与 `b` 都是静态已知的 `Float` 或 `Double` 或者它们对应的可空类型(声明为该类型，或者推断为该类型，或者[智能类型转换](https://book.kotlincn.net/text/typecasts.html#%E6%99%BA%E8%83%BD%E8%BD%AC%E6%8D%A2)的结果是该类型)，两数字所形成的操作或者区间遵循[IEEE 754 浮点运算标准](https://zh.wikipedia.org/wiki/IEEE_754)。

然而，为了支持泛型场景并提供全序支持，对于并非静态类型就是浮点数的情况，行为是不同的。

例如是 `Any`、 `Comparable<...>` 或者 `Collection<T>` 类型。 这种情况下，这些操作使用为 `Float` 与 `Double` 实现的 `equals` 与 `compareTo`。 因此：

- 认为 `NaN` 与其自身相等
- 认为 `NaN` 比包括正无穷大（`POSITIVE_INFINITY`）在内的任何其他元素都大
- 认为 `-0.0` 小于 `0.0`

下面的示例显示了静态类型为浮点数 ( `Double.NaN`) 的操作数与非静态类型为浮点数的操作数 ( `listOf(T)`) 之间的行为差 ​​ 异。

```kotlin
fun main() {
    //sampleStart
    println(Double.NaN == Double.NaN)                 // false
    println(listOf(Double.NaN) == listOf(Double.NaN)) // true
    println(0.0 == -0.0)                              // true
    println(listOf(0.0) == listOf(-0.0))              // false
    println(listOf(Double.NaN, Double.POSITIVE_INFINITY, 0.0, -0.0).sorted())
    // [-0.0, 0.0, Infinity, NaN]
    //sampleEnd
}
```

## Boolean 类型

`Boolean` 类型表示可以有 `true` 与 `false` 两个值的布尔对象。

`Boolean` 的可空版 `Boolean?` 还有 `null` 值。

布尔值的内置运算有：

- `||`——析取（逻辑或）
- `&&`——合取（逻辑与）
- `!`——否定（逻辑非）

`||` 与 `&&` 都是惰性（短路：比如：`false && someFun()`中遇到`false`就能知道此表达式一定是`false`，所以`someFunc()`不再被调用）的。

```kotlin
fun main() {
//sampleStart
    val myTrue: Boolean = true
    val myFalse: Boolean = false
    val boolNull: Boolean? = null

    println(myTrue || myFalse)
    println(myTrue && myFalse)
    println(!myTrue)
//sampleEnd
}
```

::tip
在 `JVM` 中，布尔值并不直接以一个位（`bit`）来表示，而是使用一个字节（`byte`）来存储。具体地，布尔值 `true` 被表示为字节值 `1`，而布尔值 `false` 被表示为字节值 `0`。
::


## 字符（Char）

字符用 `Char` 类型表示。 字符字面值用单引号括起来: `'1'`。

特殊字符可以以转义反斜杠 `\` 开始。 支持这几个转义序列：

- `\t`——制表符
- `\b`——退格符
- `\n`——换行（LF）
- `\r`——回车（CR）
- `\'`——单引号
- `\"`——双引号
- `\\`——反斜杠
- `\$`——美元符

编码其他字符要用 `Unicode` 转义序列语法：`'\uFF00'`。

```kotlin
fun main() {
//sampleStart
    val aChar: Char = 'a'

    println(aChar)
    println('\n') // 输出一个额外的换行符
    println('\uFF00')
//sampleEnd
}
```

## 字符串（String）

`Kotlin` 中字符串用 `String` 类型表示。 通常，字符串值是双引号（`"`）中的字符序列：

```kotlin
val str = "abcd 123"
```

字符串的元素——字符可以使用索引运算符访问: `s[i]`。 可以使用 `for` 循环遍历这些字符：

```kotlin
fun main() {
val str = "abcd"
//sampleStart
for (c in str) {
    println(c)
}
//sampleEnd
}
```

字符串是不可变的。 一旦初始化了一个字符串，就不能改变它的值或者给它赋新值。 所有转换字符串的操作都以一个新的 `String` 对象来返回结果，而保持原始字符串不变：

```kotlin
fun main() {
//sampleStart
    val str = "abcd"
    println(str.uppercase()) // 创建并输出一个新的 String 对象
    println(str) // 原始字符串保持不变
//sampleEnd
}
```

如需连接字符串，可以用 `+` 操作符（建议使用字符串模板和原始字符串实现）。这也适用于连接字符串与其他类型的值， 需要表达式中的第一个元素是字符串

### 字符串字面值

### 转义字符串

转义字符串可以包含转义字符。

以下是转义字符串的一个示例：

```kotlin
val s = "Hello, world!\n"
```

转义采用传统的反斜杠（`\`）方式。

所支持的转义序列请参见上面字符。

## 原始字符串

原始字符串可以包含换行以及任意文本。 它使用三个引号（`"""`）分界符括起来，内部没有转义并且可以包含换行以及任何其他字符：

```kotlin
val text = """
    for (c in "foo")
        print(c)
"""
```

如需删掉原始字符串中的前导空格，请使用 `trimMargin()` 函数：

```kotlin
val text = """
|Tell me and I forget.
|Teach me and I remember.
|Involve me and I learn.
|(Benjamin Franklin)
    """.trimMargin()
```

默认以竖线 `|` 作为边界前缀，但你可以选择其他字符并作为参数传入，比如 `trimMargin(">")`。

### 字符串模板

字符串字面值可以包含模板表达式——一些小段代码，会求值并把结果合并到字符串中。 模板表达式以美元符（`$`）开头，要么由一个的名称构成:

```kotlin
fun main() {
//sampleStart
    val i = 10
    println("i = $i") // 输出“i = 10”
//sampleEnd
}
```

要么是用花括号括起来的表达式:

```kotlin
fun main() {
//sampleStart
    val s = "abc"
    println("$s.length is ${s.length}") // 输出 "abc.length is 3"
//sampleEnd
}
```

在原始字符串及转义字符串中都可以使用模板。 如需在原始字符串（不支持反斜杠转义）中的允许作为标识符（`identifier`）开头的任意符号之前插入美元符 `$`， 请使用以下语法：`s`:

```kotlin
val price = """
${'$'}_9.99
"""
```

## 数组

`Kotlin` 中使用 `Array` 类来表示。它定义了 `get()` 与 `set()` 函数（按照运算符重载约定这会转变为 `[]`）与 `size` 属性及其他有用的成员函数：

下面是一些源码

````kotlin
/**
 * Represents an array (specifically, a Java array when targeting the JVM platform).
 * Array instances can be created using the [arrayOf], [arrayOfNulls] and [emptyArray]
 * standard library functions.
 * See [Kotlin language documentation](https://kotlinlang.org/docs/reference/basic-types.html#arrays)
 * for more information on arrays.
 */
public class Array<T> {
    /**
     * Creates a new array with the specified [size], where each element is calculated by calling the specified
     * [init] function.
     *
     * The function [init] is called for each array element sequentially starting from the first one.
     * It should return the value for an array element given its index.
     */
    public inline constructor(size: Int, init: (Int) -> T)

    /**
     * Returns the array element at the specified [index]. This method can be called using the
     * index operator.
     * ```
     * value = arr[index]
     * ```
     *
     * If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException] except in Kotlin/JS
     * where the behavior is unspecified.
     */
    public operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit
    operator fun iterator(): Iterator<T>
    // ......
}
````

可以使用函数 `arrayOf()` 来创建一个数组并传递元素值给它，这样 `arrayOf(1, 2, 3)` 创建了 `array [1, 2, 3]`。 或者，函数 `arrayOfNulls()` 可以用于创建一个指定大小的、所有元素都为空的数组。

另一个选项是用接受数组大小以及一个函数参数的 `Array` 构造函数，用作参数的函数能够返回给定索引的元素：

```kotlin
fun main() {
//sampleStart
    // 创建一个 Array<String> 初始化为 ["0", "1", "4", "9", "16"]
    val asc = Array(5) { i -> (i * i).toString() }
    asc.forEach { println(it) }
//sampleEnd
}
```

`[]` 运算符代表调用成员函数 `get()` 与 `set()`。

`Kotlin` 中数组是不型变的（`invariant`）。这意味着 `Kotlin` 不让我们把 `Array<String>` 赋值给 `Array<Any>`，以防止可能的运行时失败。

### 原生类型数组

`Kotlin` 也有无装箱开销的类来表示原生类型数组: `ByteArray`、 `ShortArray`、`IntArray` 等等。这些类与 `Array` 并没有继承关系，但是它们有同样的方法属性集。它们也都有相应的工厂方法:

```kotlin
// 大小为 5、值为 [0, 0, 0, 0, 0] 的整型数组
val arr = IntArray(5)

// 用常量初始化数组中的值的示例
// 大小为 5、值为 [42, 42, 42, 42, 42] 的整型数组
val arr = IntArray(5) { 42 }

// 使用 lambda 表达式初始化数组中的值的示例
// 大小为 5、值为 [0, 1, 2, 3, 4] 的整型数组（值初始化为其索引值）
var arr = IntArray(5) { it * 1 }
```

### 可变的数组

还有一种办法可以定义一个数组，那就是`List`，但是其也是不可变的，要对可变的`List`，需要使用`MutableList`定义，大部分方法都是类似的：

```kotlin
    val c:MutableList<Int> = mutableListOf(1,2,3);
    c.add(5);
    println(c);
```

## Map

`Map` 是一种键值对（`Key-Value`）的集合类型，用于存储和操作具有唯一键的元素。`Map` 接口定义了对键值对集合的基本操作，如添加、获取、删除和遍历等。

```kotlin
val m:MutableMap<String,Int> = mutableMapOf("1" to 1,);
```

## Set

`Set` 是一种集合类型，用于存储一组唯一的元素，不允许重复。`Set`接口定义了对集合的基本操作，如添加、删除、包含性检查等。

下面是可变的`Set`定义：

```kotlin
    val s:MutableSet<Int> = mutableSetOf(1,2,3,4)
    println(s);
```

## Kotlin 特有

### Pair

用于存储两个值的有序对。它提供了一种方便的方式来组合和传递两个相关的值。

```kotlin
fun main(
    Pair(1,2)
)
```

### Triple

### Any

### Nothing

### Unit

很奇怪，代表空的类型，但有不是`null`

## lateinit（延迟初始化）

`lateinit`说明可以定义一个不初始化的值，你主动告诉程序稍后你会自己初始化他。

这个很奇怪
