I've written a NaturalComparator class/object in Java and rewritten it into Scala: https://gist.github.com/319827#file_natural_comparator.scala
However, I wonder why I don't need to @SuppressWarnings("unchecked") in the Scala version. (I compile it by fsc -deprecation -unchecked NaturalComparator.scala.)
- Is Scala powerful enough to recognize that the conversion is OK?
- Does Scala compiles assume that I know what I'm doing when I'm using generics in
.asInftanceOf[...]?
Scala assumes that you know what you're doing. In this case you do know what you're doing, because even though
Comparatoris not marked as contravariant, it acts as though it is (i.e. if you can compareAnywithAny, surely you can compareTwithTfor some particularT).If you didn't know what you were doing, it would break with a runtime error.
Generally, one would use pattern matching in cases similar to this:
and now you definitely do get an unchecked warning: because
Tis erased, the match doesn't do what you think it does.