3

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.

1 Answer 1

8

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Note that using reflection like this is likely to perform much worse than explicit checks. (It also checks non-nullable properties as well -- pointlessly. And you should confirm that it works for lateinit properties, and doesn't throw an exception instead of returning false.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.