Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing values of a generic type in generic functions in Scala

Tags:

generics

scala

The following function

def compare[T] (o1:T, o2:T):Boolean = {
   o1 > o2
}

will not compile, because value > is not a member of type parameter T

Defining the parameters to be of type AnyVal also does not work, and the compiler gives a similar error.

However, the function can only be called with values of type String and Long, which do support >.

What is the recomended soultion to write such a function?

Thanks

like image 334
user1052610 Avatar asked Feb 14 '16 09:02

user1052610


2 Answers

You can use the Ordering type class like so:

def compare[T](o1: T, o2: T)(implicit ord: Ordering[T]) = ord.gt(o1, o2)
like image 103
Jason Lenderman Avatar answered Sep 27 '22 17:09

Jason Lenderman


If you want to use > operator you can use view bound with Ordered[T]

def compare[T <% Ordered[T]] (o1:T, o2:T):Boolean = {
  o1 > o2
}

There are good examples in scala docs.

http://docs.scala-lang.org/tutorials/FAQ/context-and-view-bounds.html

or you can do it with implicit parameter cause view bounds are deprecated now:

def  compare[T](o1: T, o2: T)(implicit ev: T => Ordered[T]): Boolean = {
  o1 < o2
}
like image 41
Murat Mustafin Avatar answered Sep 27 '22 17:09

Murat Mustafin