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

咨询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 if isChecked is true; otherwise it returns null.
  • The safe call operator ?. ensures let only runs if the result isn’t null, executing aMutableList.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 if blocks, making your code shorter and easier to scan.
  • The batch approach scales seamlessly—just add more devices to the listOf call 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:25:36