Reputation: 77
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
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:
data
classesUpvotes: 2