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

Kotlin如何不存储输入字符串实现空输入时赋默认值并解析?

Kotlin: Concise Input Handling Without Storing Raw String

Hey there! Awesome that you're loving Kotlin—it's such a joy to work with thanks to its focus on clean, concise code. Let's break down your question and find the best approach.

First off, your current implementation is totally valid and gets the job done. But you're right—we can definitely optimize it to avoid storing the raw input string as a separate variable, while keeping things idiomatic to Kotlin.

Here are two great alternatives:

1. Using let for inline processing

You can chain a let call directly onto readLine() to handle the null/empty check and conversion in one go, no extra variable needed:

val double = readLine().let { input ->
    if (input.isNullOrEmpty()) 0.0 else input.toDouble()
}

The let function takes the result of readLine() (which could be null) as its lambda parameter (input here, though you could use the implicit it if you prefer), so we don't need to assign it to a separate inp variable first.

2. Elvis Operator + takeIf (Even More Concise)

For an even cleaner one-liner, combine the Elvis operator (?:) with takeIf to filter out empty strings, then safely convert to a Double:

val double = readLine()?.takeIf { it.isNotEmpty() }?.toDouble() ?: 0.0

Let's break this down step by step:

  • readLine()?.takeIf { it.isNotEmpty() }: If the input isn't null and isn't empty, we keep the string; otherwise, this returns null.
  • ?.toDouble(): Safely converts the non-empty string to a Double (only runs if the previous step wasn't null).
  • If you want to handle invalid number inputs too (like if the user enters "abc" instead of a number), swap toDouble() with toDoubleOrNull() for extra robustness:
    val double = readLine()?.takeIf { it.isNotEmpty() }?.toDoubleOrNull() ?: 0.0
    
    This way, invalid numeric inputs will also fall back to the default 0.0.

Which is the best?

The second approach with takeIf and Elvis is the most idiomatic Kotlin solution here—it's concise, readable, and avoids any unnecessary variable storage. Your original code works, but this leans into Kotlin's functional features to make the code tighter.

Happy coding with Kotlin—keep exploring its awesome features!

内容的提问来源于stack exchange,提问作者Tim Gonzales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:38:43