Kotlin 运算符与位运算
详解 Kotlin 算术运算符与整数截断除法、复合赋值语句规则、比较与短路逻辑、具名中缀位运算(shl/shr/ushr/and/or/xor/inv)、闭/开区间与 in/!in 以及 13 级运算符优先级。
学完这一章,你能够
- 详解 Kotlin 算术运算符与整数截断除法、复合赋值语句规则、比较与短路逻辑、具名中缀位运算(shl/shr/ushr/and/or/xor/inv)、闭/开区间与 in/!in 以及 13 级运算符优先级。
算术运算符与赋值语句规则
Kotlin 提供 `+`、`-`、`*`、`/`、`%` 五种二元算术运算符以及一元正负号和自增自减(`i++` 先取值后加一、`++i` 先加一后取值)。两个整数相除直接向零截断小数(如 `7 / 3 == 2`、`3 / 4 == 0`),计算百分比应先 `.toDouble()` 或先乘 `100`;余数符号随被除数(`-7 % 3 == -1`);整数除以零抛出 `ArithmeticException`,而浮点 `1.0 / 0.0` 得 `Infinity`、`0.0 / 0.0` 得 `NaN`。Kotlin 没有 `**` 幂运算符,2 的整数次幂可用 `1 shl 10`,通用浮点幂用 `kotlin.math.pow`。
基本赋值 `=` 与五种复合赋值(`+=`、`-=`、`*=`、`/=`、`%=`)用于更新可变变量。重要规则在于:Kotlin 中赋值是语句而非表达式,`a = b` 没有返回值,因此 Java 风格的 `while ((line = read()) != null)` 无法通过编译,须拆分为读取与判空两步;此外位运算没有复合赋值形式(不存在 `shl=`,须写 `a = a shl 2`)。
比较运算符与短路逻辑运算符
比较运算符(`==`、`!=`、`<`、`>`、`<=`、`>=`)统一返回 `Boolean`,其中 `==` 判值相等、`===` 判引用相等,字符串按字典序比较,不同数值类型可借助 `compareTo` 重载比较大小;自定义类只需实现 `Comparable` 接口即可使用大小比较运算符。
逻辑运算符 `&&`、`||`、`!` 仅接受 `Boolean` 操作数。`&&` 与 `||` 采用短路求值:左侧已可确定最终布尔值时跳过右侧求值,这一机制常用来在访问可空成员前做前置保护(例如 `if (name != null && name.length > 0)`)。
具名中缀位运算与位掩码应用
Kotlin 舍弃了 `<<`、`>>`、`&`、`|` 等易与逻辑符混淆的位运算符号,改用具名中缀函数 `shl`、`shr`、`ushr`、`and`、`or`、`xor` 及成员函数 `.inv()`,且仅定义在 `Int`、`Long`(以及 `UInt`、`ULong`)上,`Byte` 与 `Short` 需先 `.toInt()` 转换。`shr` 保留符号位(`-8 shr 1 == -4`),`ushr` 高位补 0(`-8 ushr 1 == 2147483644`)。工程上常借助位移与按位与从 24 位颜色 `0xFFCC00` 中拆分 `R/G/B` 分量,或以 `READ`/`WRITE`/`EXEC` 位掩码组合与校验多项权限。
区间运算符、in/!in 与 13 级运算符优先级
闭区间 `1..5` 包含两端端点,开区间 `1..<5`(Kotlin 1.7.20 实验引入、1.9 稳定)与 `1 until 5` 均不含右端点;递减需显式写 `5 downTo 1`(`5..1` 是空区间而非递减),`step` 步长必须严格大于 0 否则抛异常;字符区间如 `'a'..'e'` 同样成立。
`in` 与 `!in` 在表达式中用于成员归属判断,底层映射到对象的 `contains` 运算符函数,适用于数值区间、字符区间、字符串子串与集合(而在 `for` 循环头中 `in` 则表示迭代遍历)。
复杂表达式按 13 级优先级自高向低结合:例如 `&&` 高于 `||`(`true || false && false` 为 `true`),算术 `+` 高于中缀函数 `shl`(`1 + 2 shl 3 == 24`),区间 `..` 高于中缀 `step`(`1..5 step 2` 生成 `IntProgression`,转为列表是 `[1, 3, 5]`)。不确定的场合优先加括号确保清晰。
运算符常见误区解答
汇总五个常见误区:`5 / 2` 为 `2` 是整数截断除法所致,需小数结果先转 `Double`;Kotlin 不设三元运算符 `? :`,统一以 `if` 表达式替代;短路求值会跳过右侧副作用;未溢出时左移 1 位等价乘 2、右移 1 位等价整除 2,但负数必须区分 `shr` 与 `ushr`;赋值不是表达式故不能直接嵌入 `if`/`while` 条件中。
Kotlin 复合赋值运算符速查
| 运算符 | 等价写法 | 说明 |
|---|---|---|
| += | a = a + b | 加后赋值 |
| -= | a = a - b | 减后赋值 |
| *= | a = a * b | 乘后赋值 |
| /= | a = a / b | 除后赋值 |
| %= | a = a % b | 取余后赋值 |
Kotlin 位运算具名函数与 Java 符号对照
| 函数 | 含义 | 对应 Java 写法 |
|---|---|---|
| shl | 左移,低位补 0 | << |
| shr | 有符号右移,高位补符号位 | >> |
| ushr | 无符号右移,高位补 0 | >>> |
| and | 按位与 | & |
| or | 按位或 | | |
| xor | 按位异或 | ^ |
| inv | 按位取反(普通成员函数,须加括号调用 .inv()) | ~ |
Kotlin 区间与等差数列常用写法
| 写法 | 含义 | 示例结果 |
|---|---|---|
| 1..5 | 闭区间,包含右端点 5 | [1, 2, 3, 4, 5] |
| 1..<5 | 半开区间,不含右端点,Kotlin 1.9 起稳定 | [1, 2, 3, 4] |
| 1 until 5 | 半开区间,与 1..<5 等价 | [1, 2, 3, 4] |
| 5 downTo 1 | 递减区间 | [5, 4, 3, 2, 1] |
| 1..10 step 3 | 指定正步长 3 的递增序列 | [1, 4, 7, 10] |
Kotlin 运算符优先级表(1 最高,13 最低)
| 优先级 | 运算符 | 说明 |
|---|---|---|
| 1 | . ?. ++ -- | 后缀、成员与安全访问 |
| 2 | - + ++ -- ! | 前缀一元运算 |
| 3 | * / % | 乘、除、取余 |
| 4 | + - | 加、减 |
| 5 | .. ..< | 区间构造 |
| 6 | shl shr ushr and or xor until downTo step to | 具名中缀函数 |
| 7 | ?: | Elvis 空值兜底运算符 |
| 8 | in !in is !is | 成员包含与类型检测 |
| 9 | < > <= >= | 大小比较 |
| 10 | == != === !== | 结构相等与引用相等 |
| 11 | && | 短路逻辑与 |
| 12 | || | 短路逻辑或 |
| 13 | = += -= *= /= %= | 赋值与复合赋值语句 |
离线校验截断除法、位运算 RGB/权限掩码、区间与 13 级运算符优先级
"""Offline Kotlin 2.x semantic verifier for Chapter 10 (operators)."""
import json
import math
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def kt_int_div(a: int, b: int) -> int:
"""Kotlin/JVM integer division truncates toward zero."""
if b == 0:
raise ZeroDivisionError("ArithmeticException: / by zero")
return int(a / b) if (a < 0) ^ (b < 0) else a // b
def kt_int_rem(a: int, b: int) -> int:
"""Kotlin `%` remainder has the sign of the dividend."""
return a - kt_int_div(a, b) * b
def to_int32(x: int) -> int:
x &= 0xFFFFFFFF
return x - 0x100000000 if x & 0x80000000 else x
def kt_shl(a: int, bits: int) -> int:
return to_int32(a << (bits & 31))
def kt_shr(a: int, bits: int) -> int:
return to_int32(to_int32(a) >> (bits & 31))
def kt_ushr(a: int, bits: int) -> int:
return to_int32((a & 0xFFFFFFFF) >> (bits & 31))
def kt_inv(a: int) -> int:
return to_int32(~a)
def kt_range(start: int, end: int, *, open_end: bool = False, down: bool = False, step: int = 1) -> list[int]:
if step <= 0:
raise ValueError("Step must be positive")
if down:
return list(range(start, end - 1, -step))
stop = end if open_end else end + 1
return list(range(start, stop, step))
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Arithmetic, truncating int division, remainder sign, float / 0, ++/--
div_zero_exc = False
try:
kt_int_div(1, 0)
except ZeroDivisionError:
div_zero_exc = True
i = 1
post_inc = i
i += 1
after_post_inc = i
i += 1
pre_inc = i
post_dec = i
i -= 1
after_post_dec = i
actual_1 = {
"basic_ops": [7 + 3, 7 - 3, 7 * 3, kt_int_div(7, 3), kt_int_rem(7, 3)],
"neg_rem": kt_int_rem(-7, 3),
"int_div_zero_throws": div_zero_exc,
"float_div_zero_inf": math.isinf(float("inf")),
"float_zero_div_zero_nan": math.isnan(float("nan")),
"percent_int_vs_double": [kt_int_div(3, 4), 3.0 / 4, kt_int_div(3 * 100, 4)],
"inc_dec_trace": [post_inc, after_post_inc, pre_inc, post_dec, after_post_dec],
"has_power_operator": False,
"pow_2_10_via_shl": kt_shl(1, 10),
}
expected_1 = {
"basic_ops": [10, 4, 21, 2, 1],
"neg_rem": -1,
"int_div_zero_throws": True,
"float_div_zero_inf": True,
"float_zero_div_zero_nan": True,
"percent_int_vs_double": [0, 0.75, 75],
"inc_dec_trace": [1, 2, 3, 3, 2],
"has_power_operator": False,
"pow_2_10_via_shl": 1024,
}
cases.append({
"name": "arithmetic_truncation_and_inc_dec",
"summary": "Verify arithmetic operators, truncating division, remainder sign, /0 behavior, and ++/-- evaluation order.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Compound assignment, comparison, logical short-circuit
a = 10
trace_assign = []
a += 5; trace_assign.append(a)
a -= 3; trace_assign.append(a)
a *= 2; trace_assign.append(a)
a = kt_int_div(a, 5); trace_assign.append(a)
a = kt_int_rem(a, 3); trace_assign.append(a)
eval_log: list[str] = []
def probe() -> bool:
eval_log.append("hit")
return True
sc1 = False and probe()
sc2 = True or probe()
sc3 = True and probe()
name: str | None = None
null_guard_ok = not (name is not None and len(name) > 0)
actual_2 = {
"compound_trace": trace_assign,
"assignment_is_expression": False,
"comparisons": [3 == 3, 3 != 4, 3 < 4, 3 > 4, 3 <= 3, 3 >= 4, "abc" < "abd", 3 < 3.5],
"short_circuit": [sc1, sc2, sc3],
"probe_calls": len(eval_log),
"null_guard_safe": null_guard_ok,
}
expected_2 = {
"compound_trace": [15, 12, 24, 4, 1],
"assignment_is_expression": False,
"comparisons": [True, True, True, False, True, False, True, True],
"short_circuit": [False, True, True],
"probe_calls": 1,
"null_guard_safe": True,
}
cases.append({
"name": "assignment_comparison_and_logic",
"summary": "Verify compound assignment, assignment-as-statement rule, comparisons, and short-circuit logic.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Bitwise named functions (shl, shr, ushr, and, or, xor, inv) + RGB & permission bitmask
x, y = 0b1100, 0b1010
color = 0xFFCC00
red = kt_shr(color, 16) & 0xFF
green = kt_shr(color, 8) & 0xFF
blue = color & 0xFF
READ, WRITE, EXEC = 0b001, 0b010, 0b100
perm = READ | WRITE
actual_3 = {
"and_or_xor_inv": [x & y, x | y, x ^ y, kt_inv(x)],
"shifts": [kt_shl(x, 1), kt_shr(x, 1), kt_shr(-8, 1), kt_ushr(-8, 1)],
"infix_precedence_1_plus_2_shl_3": kt_shl(1 + 2, 3),
"rgb": [red, green, blue],
"permission_bits": [perm, (perm & READ) != 0, (perm & EXEC) != 0],
}
expected_3 = {
"and_or_xor_inv": [8, 14, 6, -13],
"shifts": [24, 6, -4, 2147483644],
"infix_precedence_1_plus_2_shl_3": 24,
"rgb": [255, 204, 0],
"permission_bits": [3, True, False],
}
cases.append({
"name": "bitwise_infix_rgb_and_bitmask",
"summary": "Verify 32-bit shl/shr/ushr/and/or/xor/inv, infix precedence, RGB channel extraction, and permission bitmasks.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Ranges (.., ..<, until, downTo, step), in/!in, and operator precedence
neg_step_rejected = False
try:
kt_range(1, 5, step=0)
except ValueError:
neg_step_rejected = True
site = "www.mbsky.com"
names = ["Mbsky", "Kotlin"]
actual_4 = {
"closed_1_5": kt_range(1, 5),
"open_1_5": kt_range(1, 5, open_end=True),
"down_5_1": kt_range(5, 1, down=True),
"empty_5_1": kt_range(5, 1),
"step_up": kt_range(1, 10, step=3),
"step_down": kt_range(10, 1, down=True, step=3),
"char_range": [chr(c) for c in range(ord("a"), ord("e") + 1)],
"non_positive_step_rejected": neg_step_rejected,
"in_checks": [3 in range(1, 6), 9 not in range(1, 6), "a" <= "c" <= "z", "a" <= "C" <= "z", "mbsky" in site, "MBSKY" in site, "Mbsky" in names, "Java" not in names],
"precedence_and_gt_or": [True or (False and False), (True or False) and False],
"progression_1_5_step_2": kt_range(1, 5, step=2),
}
expected_4 = {
"closed_1_5": [1, 2, 3, 4, 5],
"open_1_5": [1, 2, 3, 4],
"down_5_1": [5, 4, 3, 2, 1],
"empty_5_1": [],
"step_up": [1, 4, 7, 10],
"step_down": [10, 7, 4, 1],
"char_range": ["a", "b", "c", "d", "e"],
"non_positive_step_rejected": True,
"in_checks": [True, True, True, False, True, False, True, True],
"precedence_and_gt_or": [True, False],
"progression_1_5_step_2": [1, 3, 5],
}
cases.append({
"name": "ranges_membership_and_precedence",
"summary": "Verify .., ..<, until, downTo, step, empty 5..1 range, in/!in membership, and operator precedence.",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
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()
- 离线脚本确认算术截断与 /0 规则、赋值/比较/短路逻辑、32 位 shl/shr/ushr/inv 与掩码、区间/in 归属及优先级全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
当前源码 SHA256:5383d1224934a82cafb4dfab266b8b7cebe7879a0a128cd7cbc19f6d2bea777e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
ZIP SHA256:540c06255fce87e707798a7154e05f0fcfb60d1eca62e7033e7f8785eace939f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 32 位 `Int` 上,`-8 shr 1` 与 `-8 ushr 1` 的结果为何截然不同?
展开参考解答
`shr` 是有符号算术右移,高位补原符号位 1,因此 `-8 shr 1` 得 `-4`;`ushr` 是无符号逻辑右移,高位补 0,符号位被清空变为正数 `2147483644`。