How to set an order for a TreeSet in Scala without repeating yourself

I have this Scala code segment that defines the order and applies it to the TreeSet. This part is compiling.

val acctOrdering = new Ordering[Account] { def compare(acc1: Account, acc2: Account) { // code to compare based on various criteria } } private var accountSet = new TreeSet[Account]()(acctOrdering) 

Elsewhere in the code, I want to get the first element in the set (and later get the next if the first does not produce what I want, although this is usually not required), based on which I pointed out earlier. I thought the following would work, but it did not compile:

 val firstAccount = accountSet.min 

Error "could not find implicit value for parameter cmp: Ordering[Account]"

However, if I specify the order object again when requesting a minimum, it will compile:

 val firstAccount = accountSet.min(acctOrdering) 

I thought that he would automatically use the ordering that I gave at build time and stepwise sorting as I add to the set, so I would not need to specify the order when calling min .

What am I doing wrong? Do I need to explicitly specify an implicit function somewhere?

+4
source share
1 answer

What happens is that you assume that min depends on the ordering of the set, but it is not. In particular, min and max are common methods available for almost any collection, and they take an implicit Ordering parameter.

However, if you try firstKey and lastKey , which are SortedSet specific methods, they will work without having to pass any implicit ones.

Edit

One question you might ask is how you can order the type of Account any method that expects Ordering . You can do this by putting an implicit definition inside the companion Account object, for example:

 object Account { implicit val ord = new Ordering[Account] { def compare(ac1: Account, acc2: Account): Int = { // code to compare based on various criteria } } } 

Once you do this, you will not need to pass the order explicitly.

+10
source

Source: https://habr.com/ru/post/1345464/


All Articles