Bruse
Bruse

Reputation: 313

Check if one field in object is not empty in 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...)

Upvotes: 3

Views: 13264

Answers (5)

Fahime Zivdar
Fahime Zivdar

Reputation: 431

val houseArray= !listOf("window", "doors", "pipes").isNullOrEmpty()

Upvotes: -1

Pawel
Pawel

Reputation: 17248

You can chain use the elvis operator which acts as a shorthand for if(x != null) x else y:

if( null != windows ?: doors ?: pipes )

This will go through each field and return the first non-null one, or null in case last element in the chain is null.

You should try to avoid allocating entire lists/arrays for such a simple comparison.

Upvotes: 4

Roland
Roland

Reputation: 23232

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

Upvotes: 5

zsmb13
zsmb13

Reputation: 89528

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 }

Upvotes: 8

tudorprodan
tudorprodan

Reputation: 965

You can use filterNotNull.

fun main(args: Array<String>) {
    var myObj = MyObj()
    myObj.house = "house"
    myObj.windows = "windows"
    print(listOf(myObj.house, myObj.windows, myObj.doors).filterNotNull());
    // prints: [house, windows]
}

class MyObj {
    var house: String? = null
    var windows: String? = null
    var doors: Int? = null
}

Upvotes: 0

Related Questions