Reputation: 319
for example, I want to check whether a is greater than b, here is a my code
def gt(a:Any,b:Any):Boolean = a match{
case a:Ordered[Any] => (a compareTo b ) > 0
case _ => false
}
however, there's more accurate way to implement this? Because the compiler give a warning:
<console>:8: warning: non-variable type argument Any in type pattern Comparable[Any] is unchecked since it is eliminated by erasure
case a:Comparable[Any] => (a compareTo b ) > 0
the implicit view should do the work,but I what I wanna do is have a function with the parameter (a:Any,b:Any), not type parameter. In java, the code maybe like this, but I don't know how to implement it in Scala way
public static boolean gt(Object a, Object b){
if(a instanceof Comparable && b.getClass() == a.getClass() ){
return ((Comparable) a).compareTo(b) > 0;
}else {
return false;
}
}
update again,I made a workable solution already, but i know it not the best way,and I will leave this question open
def ls(a: Any, b: Any): Boolean = {
a match {
case (a: Comparable[Any]) => (a compareTo b) < 0
case _ => false
}
}
Upvotes: 1
Views: 2321
Reputation: 16324
Your method will return incorrectly for some very basic cases (e.g. gt(2,1)
). You're probably looking for:
def gt[T <% Ordered[T]](a:T, b:T) = a > b
In your example, you avoid specifying a generic parameter (the parameter T
). This guarantees that the arguments to the function are of the same type, thereby attaining some type safety.
You want that type parameter to be ordered. The way this is implemented in Scala is the Ordered
trait, which takes a self type as a generic parameter.
The syntax <%
means that there needs to be an implicit conversion from T
to Ordered[T]
(called an view bound type parameter). This is true for all the standard ordered types in Scala (e.g. Int
, Char
, etc.). Without this view bound, the compiler can't know that the generic parameter is necessary ordered.
Finally, Ordered
has a >
function on it, so you don't need to use compareTo
, since it is already implemented.
You can read more about implicit views in the docs here.
You can read more about Ordered
in the docs here.
Upvotes: 4