Welcome to OGeek Q&A 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 Reply

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...