Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
question from:https://stackoverflow.com/questions/65894295/get-all-properties-from-data-class-that-are-not-null-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...