Sharone Lev
Sharone Lev

Reputation: 841

Filter on list by a generic column in Kotlin Android

I am using Kotlin and trying to filter on a generic class, therefore I don't actually have the name to go after the it.__ Is there a way of filtering on a generic column name ?

override fun getData(
    tableName: String,
    searchTerm: String?,
    columnName: String?
): List<BaseEntity> {
    for (clazz in getAllEntityClasses()) {
        if (clazz.simpleName == tableName) {
            val list = getList()
            return list.filter{it.GENERIC_COLUMNAME == searchTerm} as List<BaseEntity>
                }
            
            }
    
    return listOf()
}

Upvotes: 1

Views: 434

Answers (1)

NCuth
NCuth

Reputation: 76

If I understand correctly you want to filter the list based on the value of a field of the objects in the list. If the column name is the same as the field name then you can do something like this:

override fun getData(
    tableName: String,
    searchTerm: String?,
    columnName: String?
): List<BaseEntity> {
    for (clazz in getAllEntityClasses()) {
        if (clazz.simpleName == tableName) {
            val list = getList()
            val field = clazz.getDeclaredField(columnName)
            field.isAccessible = true
            return list.filter{field.get(it) == searchTerm} as List<BaseEntity>                    
        }
    }
    return listOf()
}

Note that it is necessary to make the field accessible otherwise private fields will throw an error.

Upvotes: 1

Related Questions