In Scala. I have two objects of type Any. If it’s possible, I’d like to cast the objects to the correct Ordered trait, and then compare them with the < method. Otherwise, I want to throw an exception. Should be simple, but I’m stumped…
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can implement this with
Orderingtype class:And then use it like this:
But this code will throw
IllegalArgumentException:Update
If you really don’t know types of objects, that you are trying to compare, then you can use this solution:
It falls down to Java’s
Comparableinterface. Generally scala has 2 traits for this purpose:Ordred– similar toComparable, but existing classes (likeStringorDate) do not implement it, so you can’t check it at runtime (at least for these classes)Ordering– it’s type class, and you can’t retrieve it at runtime.From the other hand
OrderedextendsComparableinterface, so this solution should also work for all classes that extendOrdered.