SandhyaRani D
SandhyaRani D

Reputation: 77

get all properties from data class that are not null in Kotlin

I have a data class "Sample" and wanted to collect all the values that are not null, in this case the result should be "name and "type". How to iterate over the data class members without reflection?

 data class Sample(
        var name: String = "abc",
        var model: String? = null,
        var color: String? = null,
        var type: String? = "xyz",
        var manufacturer: String? = null
    ) : Serializable

Upvotes: 1

Views: 2956

Answers (1)

Nikolai  Shevchenko
Nikolai Shevchenko

Reputation: 7521

You can use toString method of data classes and parse its output

Sample(name=abc, model=null, color=null, type=xyz, manufacturer=null)

with following code:

val nonNulls = Sample().toString()
        .substringAfter('(')
        .substringBeforeLast(')')
        .split(", ")
        .map { with(it.split("=")) { this[0] to this[1] } }
        .filter { it.second != "null" }
        .map { it.first }

println(nonNulls)

Result:

[name, type]

The obvious restrictions:

  1. Works only for data classes
  2. Ignores properties that have string value "null"

Upvotes: 2

Related Questions