Search code examples
genericsscalacastinguncheckedunchecked-conversion

Unchecked generics warning in Scala?


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[...]?

Solution

  • Scala assumes that you know what you're doing. In this case you do know what you're doing, because even though Comparator is not marked as contravariant, it acts as though it is (i.e. if you can compare Any with Any, surely you can compare T with T for some particular T).

    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:

    def cast[T](x: Any) = x match {
      case t: T => t
      case _ => throw new Exception
    }
    

    and now you definitely do get an unchecked warning: because T is erased, the match doesn't do what you think it does.