检查对象中的一个字段在kotlin中是否为空

Bru*_*use 1 kotlin

我有一个包含许多字段的对象.例:

房子
- 窗户
- 门
- 管道

我正在寻找一种优雅的方法来检查其中一个元素是否为空.代替 -if (windows != null || doors != null || pipes...)

Rol*_*and 5

你可以使用listOfNotNull,例如

val allNonNullValues = listOfNotNull(windows, doors, pipes)
if (allNonNullValues.isNotEmpty()) { // or .isEmpty() depending on what you require
// or instead just iterate over them, e.g.
allNonNullValues.forEach(::println)
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢这样,您也可以使用all,noneany例如:

if (listOf(windows, doors, pipes).any { it != null }) {
if (!listOf(windows, doors, pipes).all { it == null }) {
if (!listOf(windows, doors, pipes).none { it != null }) {
Run Code Online (Sandbox Code Playgroud)

对于您当前的情况,any-变体可能是最好的。all但是none,如果您想确保所有条目或没有条目符合特定条件(例如all { it != null }或 ) ,则获胜none { it == null }

或者,如果以上都不适合您,请提供您自己的函数,例如:

fun <T> anyNotNull(vararg elements : T) = elements.any { it != null }
Run Code Online (Sandbox Code Playgroud)

并按如下方式调用它:

if (anyNotNull(windows, doors, pipes)) {
Run Code Online (Sandbox Code Playgroud)


zsm*_*b13 5

假设您不想使用反射,您可以构建List并使用any它:

val anyElementNull = listOf(window, doors, pipes).any { it != null }
Run Code Online (Sandbox Code Playgroud)