Gustav Elmgren

01/31/2022, 6:35 PM
Hi guys, is it possible in any way to use a string to get the actual variable of a data class? Example:
data class DataStuff(val s: String, val i: Int) 

fun main() {
    val sortBy = "s"
    val myList = listOf<DataStuff>()
    val result = myList.sortedBy { it[sortBy] }
This clearly does not work, but is there any way to make it work? I won't know the value of
at runtime though...

Robert Jaros

01/31/2022, 7:07 PM
Note, reflection is only available on JVM. For multiplatform you could check


01/31/2022, 8:41 PM
This is usually not advised because it goes against type safety. How do you know the property you're trying to refer to dynamically will be comparable at all? If you're not building an actual framework that's independent from business code, I would discourage you from using reflection. If you want to dynamically refer to values based on string keys, data structures like maps are usually the go-to solution, but then you would give up on type safety for other usages of this data class if you turn it into a map. You could also map string inputs (the value of
) to properties by hand using a
expression for instance. It depends on what your overall goal is

Gustav Elmgren

01/31/2022, 8:50 PM
is user input, and if they key given does not exists on the collection of classes, an error would be returned I guess. I was thinking of doing a
expression, but for some reason I thought a customer annotation on some fields (which you can sort by) on the data class would be better. But I might doing it more complicated than what it is. KISS maybe?


01/31/2022, 9:09 PM
You can populate a map from a property name to the corresponding comparator, comparing the class by that property using compile time reflection, that should work in other platforms as well. Then use that map to query a comparator and use
function. Something like this: