2
interface Feed

class Memo : Feed {
    var memoId: String? = null
    var updateTime: String? = null
//    other fileds
}

class Activity : Feed {
    var activityId: String? = null
    var updateTime: String? = null
//    other fileds
}

As above code, I have Created one interface and extend it in the other two classes.

   var mainFeedList: ArrayList<Feed> = ArrayList()
   var memoList: ArrayList<Memo> = ArrayList()
   var ActivityList: ArrayList<Activity> = ArrayList()

    fun arrangeFeedDataOrder() {
   
        mainFeedList.addAll(memoList)
        mainFeedList.addAll(ActivityList)

        mainFeedList.sortedBy {
            when (it) {
                is Activity -> {
                    it.updateTime
                }
                is Memo -> {
                    it.updateTime
                }
                else -> {
                    null
                }
            }
        }
//        Not work above code for sorting
    }

I have the main list which contains memos and activity data. I want to sort this list with updateTime filed. I used sortedBy function but it does not work in my case. Anyone has an idea how to sort the list?

1
  • Why doesn't sortedBy work for you? You're not actually assigning the result to anything in your code, it's not an in-place sort. Commented Apr 16, 2021 at 15:34

1 Answer 1

4

You want sortBy (sorts the list in place) instead of sortedBy (returns a sorted copy, which you're basically discarding)

Also, why not put updateTime in the interface if it's something common to all Feeds? That way you don't need to do any type checking - you have a list of Feeds, they have an updateTime, so you can just sort by it.updateTime on all of them:

interface Feed {
    var updateTime: String?
}

class Memo : Feed {
    var memoId: String? = null
    override var updateTime: String? = null
}

class Activity : Feed {
    var activityId: String? = null
    override var updateTime: String? = null
}

...

mainFeedList.sortBy { it.updateTime } // or sortBy(Feed::updateTime)

or if you have a superclass for those classes, you could just define the property in there with the default null value (can't do that in an interface, which is why you need to override and provide a value in each class that implements it)

Sign up to request clarification or add additional context in comments.

5 Comments

You can't sort by a nullable.
@Tenfour04 You can? Nulls end up first in the list - pl.kotl.in/SKDs9HlkB
Wow, I never realized. Never assume.
Kotlin is doing good work rehabilitating the humble null!
@cactustictacs Thanks to kotlin.collections indeed... hahahaha the true life saver while working with lot's of data manipulation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.