Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one field in object is not empty in kotlin

Tags:

kotlin

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...)

like image 811
Bruse Avatar asked Dec 18 '25 10:12

Bruse


2 Answers

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 }
like image 80
zsmb13 Avatar answered Dec 21 '25 04:12

zsmb13


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)) {
like image 20
Roland Avatar answered Dec 21 '25 02:12

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!