wildcards in parameterized types?

Per Bothner per@bothner.com
Fri Oct 7 04:37:00 GMT 2011


On 10/06/2011 08:50 PM, Jamison Hope wrote:
> Anyway, as far as wildcards go, I don't have any good suggestions
> for good syntax to cover all the cases. Foo<?> => Foo[?] seems
> natural, and Foo<? extends Super> => Foo[Super?] seems sensible,
> but what to do about Foo<V extends Super> (which binds V to a type),
> or Foo<? super Sub>... I don't know. What do other JVM languages
> do (Scala, Clojure, ...)?

Scala uses the syntax Foo[+A] and Foo[-B], which (assuming I don't have
it backwards) is roughly equivalent Java's Foo<? extends A>
and Foo<? super B>.  However, there is one big difference between
Scala and Java: In Scala the wildcards are written in the *declaration*
of the parameterized type, while in Java they are written when a
parameterized type is *used*.  I.e. in Scala you write

   class Foo[+T] { ... }

Then if you write (say) Foo[java.util.List] that is equivalent to
Java's Foo<? extends java.util.List>.

The Java syntax is more flexible, in principle, since you can change
the variance each time you use a generic type, but it's relatively rare
this flexibility is useful.  So the Scala way of doing it is simpler,
less confusing, and less likely to be erroneous - but slightly less 
flexible.

http://www.scala-lang.org/node/129

Some other languages uses same syntax as Scala - which is orthogonal
to declaration-site vs usage-site wildcards.  It should be possible
to support both in Kawa.  For example:

(define-simple-class Bar[T] ...)
(define bar ::Bar[+number] ...)

vs

(define-simple-class Foo[+T] ...)
(define foo ::Foo[number] ...)

This could be implemented by adding an annotation to Foo
specifying the Foo has a "default wildward" which gets
automatically added when a wildcard isn't specified when Foo is used.
I.e. the translation is roughly:

class Bar<T> { ... }
Bar<? extends java.lang.Number> bar = ...;

vs

@DefaultVariance("T", EXTENDS)
class Foo<T> { ... }
Foo<? extends java.lang.Number> foo = ...;
-- 
	--Per Bothner
per@bothner.com   http://per.bothner.com/



More information about the Kawa mailing list