咨询Kotlin中简化条件判断后向MutableList添加元素的写法
Concise Ways to Replace Repetitive If Checks in Kotlin
Absolutely, Kotlin’s idiomatic features are made for cleaning up this kind of repetitive conditional code! Here are a few elegant alternatives to your original if blocks:
1. Use takeIf + Safe Call for Individual Checks
This is a direct replacement for your original code that cuts down on boilerplate:
mBluetoothDef.takeIf { it.isChecked }?.let(aMutableList::add) mWiFiDef.takeIf { it.isChecked }?.let(aMutableList::add)
How it works:
takeIf { it.isChecked }returns the device object only ifisCheckedistrue; otherwise it returnsnull.- The safe call operator
?.ensuresletonly runs if the result isn’t null, executingaMutableList.add(it)in that case.
2. Batch Filter & Add (Better for Scalability)
If you might add more device types later, this approach is far more maintainable. It groups all your devices, filters the selected ones, and adds them in one go:
// Option 1: Explicit intermediate step (great for readability) val selectedDevices = listOf(mBluetoothDef, mWiFiDef).filter { it.isChecked } aMutableList.addAll(selectedDevices) // Option 2: Compact one-liner aMutableList.addAll(listOf(mBluetoothDef, mWiFiDef).filter { it.isChecked })
If you’re initializing aMutableList directly (instead of adding to an existing list), you can simplify even further:
val aMutableList = listOf(mBluetoothDef, mWiFiDef) .filter { it.isChecked } .toMutableList()
Why These Are Better
- They eliminate repetitive
ifblocks, making your code shorter and easier to scan. - The batch approach scales seamlessly—just add more devices to the
listOfcall if you need to support other types later. - All methods are idiomatic Kotlin, aligning with the language’s focus on conciseness and readability.
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

