I have an object which include many fields. example:
House
- windows
- doors
- pipes
etc.
I'm looking for an elegant way to check if one of the element is not null.
instead of - if (windows != null || doors != null || pipes...)
Assuming you don't want to use reflection, you can build a List and use any on it:
val anyElementNull = listOf(window, doors, pipes).any { it != null }
You could use listOfNotNull, e.g.
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)
If you do not like that, you can also use all, none or any e.g.:
if (listOf(windows, doors, pipes).any { it != null }) {
if (!listOf(windows, doors, pipes).all { it == null }) {
if (!listOf(windows, doors, pipes).none { it != null }) {
For your current condition the any-variant is probably the nicest. all and none however win if you want to ensure that all or none of the entries match a certain criteria, e.g. all { it != null } or none { it == null }.
Or if none of the above really fits you, supply your own function instead, e.g.:
fun <T> anyNotNull(vararg elements : T) = elements.any { it != null }
and call it as follows:
if (anyNotNull(windows, doors, pipes)) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With