What mechanism does Scala have for generics and wildcards compared to Java?

I often push the limits of the Java type system by using Guice, typeliteral, generics and wildcards I often encounter the need to execute an unchecked cast, which almost destroys type safety - in other words, "generic hell"

This is a simplified example of some of my problematic java code

class SquareDrawer implements ShapeDrawer<Row<Square>> {}
class Client {
   Key<SquareDrawer> SQUARE_DRAWER_KEY = 
      Key.get(SquareDrawer.class,randomAnnotation());
   void bindShapeDrawer(
      Key<? extends ShapeDrawer<Row<? extends Shape>>> shapeDrawer) {}

   Client() {
      // Note Unchecked cast required below
      bindShapeDrawer( 
         (Key<? extends ShapeDrawer<Row<? extends Shape>>>) SQUARE_DRAWER_KEY);
   }
}

I've been learning Scala and always think it supports generics better than Java Can the above code be written in scala to avoid unchecked casting?

Do you still need Guice's typeliteral in scala?

Solution

Scala provides something

>The more advanced kind type (I hope I use this term correctly) allows you to define things such as "any type has another type as a type parameter". AFAIK has no way to express > CO and contravariant type parameters in Java In Java, you can create parameters by using wildcards wherever they are used In Scala, you simply declare them. > Type witness (again: is this the correct term?) Are implicit functions that demonstrate certain properties of type parameters and define constraints on types If there is an implicit conversion that matches the witness declaration, the call will compile the condition. > Path dependency type You can have types as instance elements, so each instance has its own type Again, you can't do this in Java AFAIK

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>