You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Kotlin惯用写法简化Android Bundle相关的when表达式?

Idiomatic Kotlin Solutions for Your Bundle Value Retrieval

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:49:16