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
You can use the Ordering
type class like so:
def compare[T](o1: T, o2: T)(implicit ord: Ordering[T]) = ord.gt(o1, o2)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With