Andranik
Andranik

Reputation: 2849

Kotlin check if data class properties are all null

Suppose I have a data class with nullable properties:

data class User(
   val fName: String?,
   val lName: String?)

In a function where I receive an instance of such a class even if the instance is not null I want to check that at least one of the properties inside is initialized and not null. I know that I can check the properties one by one, but I want to have something more generic, I googled and seems Kotlin there is no extension function for this so I implemented one and would like to share with you and check if anyone knows better ways.

Upvotes: 3

Views: 5555

Answers (1)

Andranik
Andranik

Reputation: 2849

So this can be done using Kotlin reflection and here is an extension function to do this:

fun Any.isAllNullInside(): Boolean {
     if(this::class.declaredMemberProperties.any { !it.returnType.isMarkedNullable }) return false
     return this::class.declaredMemberProperties.none { it.getter.call(this) != null }
}

@gidds thanks for a good catch. I understand that it will perform worse, but any solution based on reflection will perform worse than if it will be done by hand. But if it's fine to loose some small performance but have generic solution I guess reflection is very powerful mechanism.

Related to the non nullable properties and lateinit vars, I have added a line of code which fixes both. Thanks for a catch!

Upvotes: 8

Related Questions