Kotlin 基本数据类型
系统解析 Kotlin 六种有符号数值类型与位宽溢出、字面量规则、禁止隐式拓宽与显式 toX 转换、无符号整数、== 与 === 装箱缓存、Boolean 短路、Char 及不协变数组。
学完这一章,你能够
- 系统解析 Kotlin 六种有符号数值类型与位宽溢出、字面量规则、禁止隐式拓宽与显式 toX 转换、无符号整数、== 与 === 装箱缓存、Boolean 短路、Char 及不协变数组。
数值类型位宽、装箱机制与溢出边界
Kotlin 静态类型体系涵盖数值类型(`Byte`、`Short`、`Int`、`Long`、`Float`、`Double`)、布尔类型 `Boolean`、字符类型 `Char`、字符串 `String` 及数组等;与 Java 的重要差异在于 `Char` 在 Kotlin 中不属于数值类型,不可直接参与算术运算。在 JVM 上,非空 `Int`/`Long`/`Double` 默认直接映射为底层原始类型 `int`/`long`/`double`,零对象分配开销;仅当声明为可空类型(如 `Int?`)或放入泛型容器时才触发装箱(boxing)。
各定宽整数类型超出上下界时会按二进制补码静默回绕溢出而不抛异常,例如 `Int.MAX_VALUE + 1` 变为 `-2147483648`,`Int.MIN_VALUE - 1` 变为 `2147483647`。涉及金融金额或大跨度时间戳时,应主动边界校验或改用 `Long`(先调用 `.toLong()` 再运算)乃至 `BigInteger`。
字面常量、禁止隐式转换与无符号整数
Kotlin 整数字面量支持十进制、十六进制(`0x`)和二进制(`0b`),但明确不支持八进制写法(切勿沿用 C/Java 的前导 `0` 写法如 `0755`,Kotlin 不会将其按八进制 493 解析)。数值字面量可在数字之间插入下划线分隔(如 `1_000_000`、`0xFF_EC_DE`、`0b1101_0010`),但不可放在首尾或紧邻小数点;浮点默认推断为 `Double`,`Float` 需显式加 `f`/`F` 后缀。
Kotlin 取消了数值间的隐式拓宽转换:即便是 `Byte` 赋给 `Int` 变量也必须显式调用 `.toInt()`;唯一例外是编译期可静态验证范围的整数字面量(如 `val b2: Byte = 100`)以及混合算术表达式(`1L + 3` 结果为 `Long`)。所有数值类型均提供完整的 `toByte()` 至 `toULong()` 转换函数:窄化转换(如 `300.toByte()` 得到 `44`)按低位截断,浮点转整数(如 `3.99.toInt()` 得到 `3`)直接截断小数部分,如需四舍五入应调用 `kotlin.math.roundToInt()`。
Kotlin 1.3 引入、1.5 稳定的无符号整数类型包括 `UByte`、`UShort`、`UInt` 与 `ULong`,正数上限约为同位宽有符号类型的两倍(配套无符号数组如 `UByteArray` 仍属 Beta,需 `@ExperimentalUnsignedTypes`)。字面量使用 `u`/`U`/`uL`/`UL` 后缀。无符号类型并非有符号类型的子类型,二者不可混用;工程上无符号类型主要面向颜色码 `0xFFCC00CCu` 等位模式表达,而非用来约束业务“非负数”(例如集合索引仍应使用 `Int` 以兼容空集合 `lastIndex == -1`)。
数字相等性比较:== 与 === 及跨类型 compareTo
`==` 判断结构(值)相等,`===` 判断引用相等。对非空原始表示的 `Int`、`Long`、`Double`,`===` 在运行期退化为与 `==` 等价(因此 `val x: Int = 1000; val y: Int = 1000` 时 `x === y` 为 `true`,且编译器会对数值使用 `===` 发出弃用或禁止警告)。仅当装箱为可空类型 `Int?` 时才体现引用差异:`-128..127` 命中 JVM `Integer` 缓存故 `100 === 100` 为 `true`,而 `1000` 超出缓存区故两个装箱对象 `p === q` 为 `false`。
不同数值类型之间不能用 `==` 直接判等(`Int == Double` 会编译报错);但 `<`、`>`、`<=`、`>=` 允许跨类型比较,这是因为标准库重载了 `Int.compareTo(Double)` 等方法,而并非 Kotlin 执行了隐式类型转换。
Boolean 短路运算、Char 字符类型与不协变数组
`Boolean` 仅包含 `true` 与 `false` 两值,支持短路逻辑运算符 `&&`、`||` 与 `!`(左侧已决定结果时不求值右侧),同时也提供函数形式 `and`、`or`、`xor` 与 `not()`。可空布尔 `Boolean?` 同样会发生装箱。
`Char` 字面量用单引号包裹(如 `'A'`),不可直接赋值给 `Int` 或与数字比较;自 Kotlin 1.5 起推荐使用 `.code` 获取 Unicode 码点(取代已弃用的 `Char.toInt()`),数字字符转数值使用 `.digitToInt()`(非数字字符将抛异常)。支持 `Char + Int -> Char` 与 `Char - Char -> Int`,以及 `\t`、`\n`、`\$`、`\uXXXX` 等九类转义序列。
通用数组 `Array<T>` 可通过 `arrayOf(...)`、`Array(size) { it * 2 }` 或 `arrayOfNulls<String>(n)` 构建,支持 `[]` 下标读写与 `.contentToString()` 展示;性能敏感场景应优先使用无装箱的 `IntArray`、`DoubleArray`、`CharArray` 等原始类型数组。与 Java 数组不同,Kotlin 的 `Array<T>` 是不协变的(invariant):`Array<String>` 并非 `Array<Any>` 的子类型,从而将 Java 运行期的 `ArrayStoreException` 提前至编译期拦截。数组长度固定,需要动态增删时请选用 `List`/`MutableList`。
基本数据类型常见问题排查
高频疑问集中在五点:第一,`val b: Byte = 100` 合法而 `val i: Int = b` 报错,是因为字面量可在编译期静态确认范围而变量不行;第二,浮点默认优先 `Double`,仅在内存极端受限或对接特定 API 时用 `Float`;第三,毫秒时间戳、大主键 ID 与文件字节数等易超 21 亿的值应选 `Long` 并记得写 `L` 后缀;第四,`IntArray` 对应 `int[]` 无装箱开销,`Array<Int>` 可放泛型且支持可空 `Array<Int?>`;第五,`Char` 独立于数值体系,比较码点需 `.code`,数字字符转整数需 `.digitToInt()`。
Kotlin 六种有符号数值类型位宽与取值范围
| 类型 | 位宽 | 取值范围 | 说明 |
| Byte | 8 | -128 ~ 127 | 最小有符号整数类型。 |
| Short | 16 | -32768 ~ 32767 | 16 位短整型,日常较少使用。 |
| Int | 32 | -2147483648 ~ 2147483647 | 整数字面量的默认类型。 |
| Long | 64 | -9223372036854775808 ~ 9223372036854775807 | 64 位长整型,字面量需加 L 后缀。 |
| Float | 32 | 约 ±3.4×10³⁸ | 单精度浮点(6~7 位有效数字),字面量加 f/F 后缀。 |
| Double | 64 | 约 ±1.8×10³⁰⁸ | 双精度浮点(15~16 位有效数字),浮点默认类型。 |
Kotlin 数值字面量写法汇总
| 写法 | 示例 | 说明 |
| 十进制 | 123 | 默认推断为 Int。 |
| 十六进制 | 0x0F | 0x/0X 前缀,十六进制字母大小写均可。 |
| 二进制 | 0b00001011 | 0b/0B 前缀。 |
| 八进制 | 无 | Kotlin 不支持八进制整数字面量。 |
| Long | 123L | 大写 L 后缀;超出 Int 范围的字面量也会推断为 Long。 |
| Double | 123.5、123.5e10 | 小数及科学计数法默认推断为 Double。 |
| Float | 123.5f | 加 f 或 F 后缀指定单精度 Float。 |
| 下划线分隔 | 1_000_000 | 仅提升可读性,编译期忽略下划线。 |
Int 上的显式数值转换函数清单
| 函数 | 返回类型 | 说明 |
| toByte() | Byte | 超出 Byte 范围时按低 8 位截断。 |
| toShort() | Short | 超出 Short 范围时按低 16 位截断。 |
| toInt() | Int | 返回当前 Int 自身。 |
| toLong() | Long | 安全拓宽至 64 位长整型。 |
| toFloat() | Float | 大整数转单精度浮点可能丢失有效精度。 |
| toDouble() | Double | 转换为 64 位双精度浮点。 |
| toChar() | Char | 将码点整数转换为对应 Unicode 字符。 |
| toUByte() | UByte | Kotlin 1.5 起稳定,转为 8 位无符号整数。 |
| toUShort() | UShort | Kotlin 1.5 起稳定,转为 16 位无符号整数。 |
| toUInt() | UInt | Kotlin 1.5 起稳定,转为 32 位无符号整数。 |
| toULong() | ULong | Kotlin 1.5 起稳定,转为 64 位无符号整数。 |
Kotlin 无符号整数类型(Kotlin 1.5 起稳定)
| 类型 | 位宽 | 取值范围 |
| UByte | 8 | 0 ~ 255 |
| UShort | 16 | 0 ~ 65535 |
| UInt | 32 | 0 ~ 4294967295 |
| ULong | 64 | 0 ~ 18446744073709551615 |
Kotlin 字符与字符串转义序列
| 转义序列 | 含义 |
| \t | 制表符(Tab) |
| \b | 退格符(Backspace) |
| \n | 换行符(LF) |
| \r | 回车符(CR) |
| \' | 单引号字符 |
| \" | 双引号字符 |
| \\ | 反斜杠本身 |
| \$ | 字面量美元符号,阻止触发字符串模板 |
| \uXXXX | 四位十六进制表示的 Unicode 字符 |
离线校验数值位宽溢出、显式转换、Int? 装箱缓存、短路布尔、Char 与数组不协变
展开查看收起
"""Offline Kotlin 2.x semantic verifier for Chapter 08 (basic-types)."""
import json
import math
import struct
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def to_signed(val: int, bits: int) -> int:
mask = (1 << bits) - 1
v = val & mask
return v - (1 << bits) if v >= (1 << (bits - 1)) else v
def to_unsigned(val: int, bits: int) -> int:
return val & ((1 << bits) - 1)
def to_float32(val: float) -> float:
return struct.unpack("<f", struct.pack("<f", val))[0]
class BoxedInt:
"""Models JVM boxed Integer (Kotlin Int?) with -128..127 integer cache."""
_cache: dict[int, "BoxedInt"] = {}
def __init__(self, value: int) -> None:
self.value = to_signed(value, 32)
@classmethod
def box(cls, value: int) -> "BoxedInt":
v = to_signed(value, 32)
if -128 <= v <= 127:
if v not in cls._cache:
cls._cache[v] = cls(v)
return cls._cache[v]
return cls(v)
def __eq__(self, other: object) -> bool:
return isinstance(other, BoxedInt) and self.value == other.value
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Signed numeric ranges & 32-bit two's-complement wraparound overflow
int_max = (1 << 31) - 1
int_min = -(1 << 31)
overflow_up = to_signed(int_max + 1, 32)
overflow_down = to_signed(int_min - 1, 32)
long_safe = to_signed(int_max + 1, 64)
actual_1 = {
"byte_range": [-128, 127],
"short_range": [-32768, 32767],
"int_max": int_max,
"int_min": int_min,
"int_max_plus_1": overflow_up,
"int_min_minus_1": overflow_down,
"long_plus_1": long_safe,
}
expected_1 = {
"byte_range": [-128, 127],
"short_range": [-32768, 32767],
"int_max": 2147483647,
"int_min": -2147483648,
"int_max_plus_1": -2147483648,
"int_min_minus_1": 2147483647,
"long_plus_1": 2147483648,
}
cases.append({
"name": "numeric_bitwidth_and_overflow",
"summary": "Verify Byte/Short/Int/Long ranges and 32-bit Int wraparound overflow vs 64-bit Long widening.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Literals (dec, hex, bin, underscores, float/double, no octal)
actual_2 = {
"dec": 123,
"hex": 0x0F,
"bin": 0b00001011,
"underscores": 1_000_000,
"hex_bytes": 0xFF_EC_DE,
"bin_bytes": 0b1101_0010,
"double_sci": 123.5e10,
"float32_3_14_approx": round(to_float32(3.14), 6),
"octal_supported": False,
}
expected_2 = {
"dec": 123,
"hex": 15,
"bin": 11,
"underscores": 1000000,
"hex_bytes": 16772318,
"bin_bytes": 210,
"double_sci": 1.235e12,
"float32_3_14_approx": 3.14,
"octal_supported": False,
}
cases.append({
"name": "numeric_literals_and_underscores",
"summary": "Verify decimal, hex, binary, underscore grouping, scientific notation, and absence of octal literals.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: No implicit widening + explicit toX() conversions + unsigned types
i_val = 65
d_val = 3.99
big_int = 300
u_val = to_unsigned(42, 32)
actual_3 = {
"implicit_byte_to_int_allowed": False,
"literal_100_to_byte_allowed": True,
"int65_to_char": chr(i_val),
"double_3_99_trunc_to_int": int(math.trunc(d_val)),
"double_3_99_round": round(d_val),
"int300_to_byte_trunc": to_signed(big_int, 8),
"uint_max": (1 << 32) - 1,
"ulong_max": (1 << 64) - 1,
"ubyte_0xff": to_unsigned(0xFF, 8),
"uint_add": to_unsigned(u_val + 1, 32),
}
expected_3 = {
"implicit_byte_to_int_allowed": False,
"literal_100_to_byte_allowed": True,
"int65_to_char": "A",
"double_3_99_trunc_to_int": 3,
"double_3_99_round": 4,
"int300_to_byte_trunc": 44,
"uint_max": 4294967295,
"ulong_max": 18446744073709551615,
"ubyte_0xff": 255,
"uint_add": 43,
}
cases.append({
"name": "explicit_conversions_and_unsigned_types",
"summary": "Verify explicit toByte/toInt/toChar truncation semantics and UByte/UShort/UInt/ULong bounds.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: == vs === (primitive Int vs boxed Int? cache -128..127) & cross-type compareTo
p = BoxedInt.box(1000)
q = BoxedInt.box(1000)
m = BoxedInt.box(100)
n = BoxedInt.box(100)
i5, d5 = 5, 5.0
cmp_i_d = -1 if i5 < d5 else (1 if i5 > d5 else 0)
actual_4 = {
"primitive_int_1000_eq": 1000 == 1000,
"primitive_int_1000_ref_eq_degenerates_to_val_eq": True,
"boxed_1000_struct_eq": p == q,
"boxed_1000_ref_eq": p is q,
"boxed_100_ref_eq_cached": m is n,
"cross_type_eq_int_double_allowed": False,
"cross_type_compareTo": cmp_i_d,
"int5_gt_4_9": i5 > 4.9,
}
expected_4 = {
"primitive_int_1000_eq": True,
"primitive_int_1000_ref_eq_degenerates_to_val_eq": True,
"boxed_1000_struct_eq": True,
"boxed_1000_ref_eq": False,
"boxed_100_ref_eq_cached": True,
"cross_type_eq_int_double_allowed": False,
"cross_type_compareTo": 0,
"int5_gt_4_9": True,
}
cases.append({
"name": "equality_boxing_cache_and_compareTo",
"summary": "Verify primitive == vs ===, boxed Int? JVM cache (-128..127), and cross-type Int.compareTo(Double).",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: Boolean short-circuiting & Char (.code, arithmetic, digitToInt, escapes)
calls: list[str] = []
def check() -> bool:
calls.append("called")
return True
r1 = False and check()
r2 = True or check()
r3 = True and check()
ch = "A"
digit_5 = int("5")
actual_5 = {
"short_circuit_results": [r1, r2, r3],
"check_call_count": len(calls),
"xor_true_false": True ^ False,
"char_code": ord(ch),
"char_plus_1": chr(ord(ch) + 1),
"char_diff": ord(ch) - ord("A"),
"digit_to_int": digit_5,
"unicode_escape_0041": "\u0041",
}
expected_5 = {
"short_circuit_results": [False, True, True],
"check_call_count": 1,
"xor_true_false": True,
"char_code": 65,
"char_plus_1": "B",
"char_diff": 0,
"digit_to_int": 5,
"unicode_escape_0041": "A",
}
cases.append({
"name": "boolean_short_circuit_and_char_semantics",
"summary": "Verify Boolean short-circuit evaluation, Char.code, Char arithmetic, digitToInt, and Unicode escapes.",
"expected": expected_5,
"actual": actual_5,
"passed": actual_5 == expected_5,
})
# Case 6: Array<T>, IntArray, arrayOfNulls, 2D array & array invariance
a = [1, 2, 3]
b = [i * 2 for i in range(3)]
a[0] = 100
ints = [1, 2, 3]
ints[0] = ints[1] + ints[2]
squares = [i * i for i in range(5)]
nulls = [None, None]
grid = [[0, 0, 0] for _ in range(2)]
grid[1][2] = 9
actual_6 = {
"a_after_set": a,
"factory_b": b,
"int_array_after_set": ints,
"squares": squares,
"nulls": nulls,
"grid_row1": grid[1],
"array_covariant_in_kotlin": False,
}
expected_6 = {
"a_after_set": [100, 2, 3],
"factory_b": [0, 2, 4],
"int_array_after_set": [5, 2, 3],
"squares": [0, 1, 4, 9, 16],
"nulls": [None, None],
"grid_row1": [0, 0, 9],
"array_covariant_in_kotlin": False,
}
cases.append({
"name": "arrays_primitive_arrays_and_invariance",
"summary": "Verify arrayOf, Array(size){}, IntArray, arrayOfNulls, 2D grids, and Kotlin Array<T> invariance.",
"expected": expected_6,
"actual": actual_6,
"passed": actual_6 == expected_6,
})
return cases
def main() -> None:
payload = {"version": VERSION, "cases": run_cases()}
sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
非空 `Int` 在 JVM 上使用基本类型 `int`,`===` 退化为值比较;而可空 `Int?` 会装箱成 `Integer` 对象,1000 超出了 `-128..127` 的 JVM 缓存区间,导致两次装箱创建了两个不同引用。