Kotlin如何不存储输入字符串实现空输入时赋默认值并解析?
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'tnulland isn't empty, we keep the string; otherwise, this returnsnull.?.toDouble(): Safely converts the non-empty string to a Double (only runs if the previous step wasn'tnull).- If you want to handle invalid number inputs too (like if the user enters "abc" instead of a number), swap
toDouble()withtoDoubleOrNull()for extra robustness:
This way, invalid numeric inputs will also fall back to the default 0.0.val double = readLine()?.takeIf { it.isNotEmpty() }?.toDoubleOrNull() ?: 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

