今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

⚠️ The Kotlin Multiplatform division-by-zero trap

Kotools 2026年06月13日 20:40 3 次阅读 来源:Dev.to

If you write Kotlin Multiplatform code that involves integer division, you may have already hit this: the exact same expression behaves completely differently depending on which platform compiles it. 🐛 The problem Take this innocuous expression: val quotient = 12 / 0 val remainder = 12 % 0 On JVM and Native , both lines throw an ArithmeticException . That is the behavior most Kotlin developers expect and design around. On JavaScript , both lines execute without any exception and silently return 0 . Here is a concrete illustration drawn directly from the Kotlin test suites for each platform: // Kotlin/JS check ( 12 / 0 == 0 ) // passes — no exception check ( 12 % 0 == 0 ) // passes — no exception // Kotlin/JVM and Kotlin/Native val quotient : Result < Int > = runCatching { 12 / 0 } val remainder : Result < Int > = runCatching { 12 % 0 } check ( quotient . exceptionOrNull () is ArithmeticException ) // passes check ( remainder . exceptionOrNull () is ArithmeticException ) // passes Summary table: Expression JVM / Native JavaScript 12 / 0 ArithmeticException 0 12 % 0 ArithmeticException 0 🤔 Why it happens On Kotlin/JS, Int values are represented as JavaScript numbers, and 12 / 0 evaluates to Infinity while 12 % 0 evaluates to NaN . Kotlin/JS truncates Int arithmetic to 32 bits using JavaScript's | 0 operator, and per the ECMAScript ToInt32 conversion, both Infinity | 0 and NaN | 0 evaluate to 0 — so the division-by-zero result silently becomes 0 , with no exception thrown. JVM and Native follow Java's long-standing contract: integer division by zero is always an ArithmeticException . The practical consequence is that any guard you write and test on JVM — a try/catch(ArithmeticException) or a pre-condition check that relies on an exception — is silently bypassed when the same code runs on JS. No compile error, no warning, just a wrong result. ✅ The fix: Integer from Kotools Types 5.1.1 The Integer type in Kotools Types explicitly checks for a zero divisor before delegat

本文内容来源于互联网,版权归原作者所有
查看原文