Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an Ordering in Scala?

Having val hm: HashMap[org.joda.time.DateTime, MyType] I am trying to get the first and the last DateTime of the set by means of hm.keys.min and hm.keys.max respectively but the compiler says No implicit Ordering defined for org.joda.time.DateTime. How to define this ordering (both implicit and explicit options are interesting)?

like image 811
Ivan Avatar asked Jan 30 '12 08:01

Ivan


People also ask

How do I sort a list in Scala?

Use the sortWith() Function to Sort List in Scala. We used the sortWith() function to take a lambda expression as an argument and return the sorted result. We can use this function to sort the list in ascending and descending order.

What is implicit ordering?

Implicit means the order of items (e.g. codes) as returned within the array of codes. There are thus always naturally given in a structure definition. Explicit order is the order provided through annotations and is optional. Explicit order prevails implicit order.

How do you sort a set in Scala?

The first two methods that are used here ("SortedSet" and "TreeSet") are used to sort immutable sets in Scala and take set as input and return the sorted set. The last method is SortedSet working over mutable sets too and take the list conversion of the set to sort.


2 Answers

object Joda {     implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_ isBefore _) }  // elsewhere import Joda._ dateTimes.sorted 
like image 183
retronym Avatar answered Sep 20 '22 17:09

retronym


To facilitate working with Joda DateTime in Scala, nscala-time was created: https://github.com/nscala-time/nscala-time

After including it in your project with

libraryDependencies += "com.github.nscala-time" %% "nscala-time" % "1.8.0" 

you can just import OrderingImplicits. Either all at once:

import com.github.nscala_time.time.OrderingImplicits._ 

or a particular one:

import com.github.nscala_time.time.OrderingImplicits.DateTimeOrdering 
like image 26
Majki Avatar answered Sep 19 '22 17:09

Majki