Kotlin中Long转Int无报错?误用getInt获Long参数返回0值问题
Understanding Why
getInt("id") Returns 0 Instead of an Error, and Kotlin's Type Conversion Behavior Let me walk you through why you're seeing this confusing behavior, and how to avoid similar headaches in the future.
Why does intent.extras.getInt("id") return 0 instead of throwing an error?
Android's Bundle class is built to prioritize app stability over strict type enforcement. Here's what's happening:
- When you call
getInt()for a key that maps to a non-Intvalue (like your storedLong), or if the key doesn't exist at all, the method silently returns the default value for the primitiveInttype—which is 0. - This design choice prevents your app from crashing immediately, but it creates a debugging blind spot: you don't get an explicit warning that you're trying to retrieve the wrong data type. The
Bundledoesn't attempt to convert theLongto anInt; it just can't find anIntmatching your key, so it falls back to 0.
Why doesn't Kotlin warn about this Long-to-Int mismatch?
There are two key reasons for this:
- Bundle is dynamically typed: At compile time, Kotlin has no way to know what data types are stored in the
Bundle. The compiler can't verify that "id" is associated with aLonginstead of anInt, so it can't flag this as a mistake. - Primitive conversion behavior: Even if you did an explicit cast like
val myId: Int = longId.toInt(), Kotlin (and the underlying JVM) will silently truncate the value if theLongexceeds the range ofInt—it won't throw an exception by default. This is a holdover from Java's type handling, where primitive conversions are implicit and uncheckable unless you use specific utility methods.
How to fix this and avoid similar issues
Here are practical steps to make your code safer and easier to debug:
- Match getters to stored types: Always use the getter that matches the data type you stored. In your case, replace
getInt("id")withgetLong("id")to retrieve theLongvalue directly. - Use nullable getters for clarity: If you're using AndroidX, leverage
getLongOrNull("id")—this returnsnullinstead of 0 when the key is missing or the type is wrong. Anullvalue makes it immediately obvious something's off, so you can handle the issue explicitly instead of chasing a misleading 0. - Adopt type-safe argument passing: For more robust code, use
Parcelabledata classes or Jetpack'sSavedStateHandle(for ViewModels) to pass arguments. These enforce type safety at compile time, so you can't accidentally use the wrong type when retrieving values. - Use checked conversions when needed: If you ever need to convert a
Longto anIntintentionally, uselongValue.toIntExact()from Kotlin's standard library. This throws anArithmeticExceptionif the value is too large/small to fit in anInt, alerting you immediately to the problem.
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

