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

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...