如何用Kotlin惯用写法简化Android Bundle相关的when表达式?
Hey there! Let's get that code cleaned up to fit Kotlin's style. Your goal is to fetch KEY_DOWN_X from the arguments Bundle if it's present, otherwise return centerX()—here are a few solid, idiomatic ways to do this:
1. Use Bundle's Built-in Default Value Overload (Simplest)
Android's Bundle class already has an overload of getInt that accepts a default value, which makes this the most straightforward solution:
private fun getTouchX(): Int = arguments.getInt(KEY_DOWN_X, centerX())
If KEY_DOWN_X isn't present in the Bundle, it automatically returns your centerX() value. No extra conditionals needed! Just note: this assumes arguments is never null. If it could be null, add a null check:
private fun getTouchX(): Int = arguments?.getInt(KEY_DOWN_X, centerX()) ?: centerX()
2. Correct the When Expression Syntax
Your original when attempt had a syntax error—Kotlin's when as a conditional expression (without a target value) uses the when {} block format. Here's the fixed version:
private fun getTouchX(): Int = when { arguments.containsKey(KEY_DOWN_X) -> arguments.getInt(KEY_DOWN_X) else -> centerX() }
This is great if you need to add more complex conditions later, but for this simple case, the first method is more concise.
3. Chain with TakeIf (Functional Style)
If you prefer Kotlin's functional programming style, use takeIf to check for the key, then safely retrieve the value, falling back to centerX() with the elvis operator:
private fun getTouchX(): Int = arguments.takeIf { it.containsKey(KEY_DOWN_X) }?.getInt(KEY_DOWN_X) ?: centerX()
This keeps everything in a single line and reads like a sequence of checks: "take the arguments only if it has the key, get the value, or else use centerX()".
All of these follow Kotlin's idioms—pick the one that fits your codebase's style best!
内容的提问来源于stack exchange,提问作者Bansook Nam

