More Typing Problems

Maurizio Cimadamore maurizio.cimadamore at
Tue Sep 7 01:24:58 PDT 2010

On 06/09/10 22:39, Ming-Yee Iu wrote:
> I'm having more problems with getting my code to type properly. The
> following piece of code does not compile due to typing problems:
The problem you are reporting is related to how javac type-inference 
works (in general, not in this lambda extension).
In your example, you need the target type DBSet<String> in order to 
correctly type the call to select(...) [as the return type of this 
method is 'open', since U cannot be instantiated from the supplied 
actual argument, as the lambda has untyped parameters].

Unfortunately, if you chain multiple method calls, the target type will 
be used only for the last call in the chain, namely the one to 
'sortedByStringAscending(...)', meaning that the call to 'select(...)' 
will have U inferred to the 'default' type Object, thus causing a 
compilation error.

We could write a similar example in plain Java (with generics) w/o 
lambda expressions.

> public class Test
> {
>     public static class Customer {
>        public String getName() { return "";}
>     }
>     public abstract static class StringSorter<U>  {
>        abstract String value(U val);
>     }
>     public static interface Select<U, V>  {
>        public V select(U val);
>     }
>     public static class DBSet<T>   {
>        public<U>  DBSet<U>  select(Select<T,U>  x) {return new DBSet<U>();}
>        public DBSet<T>  sortedByStringAscending(StringSorter<T>  x) {return this;}
>     }
>     public static DBSet<Customer>  allCustomer()
>     {
>        return new DBSet<Customer>();
>     }
>     public static void main(String[] args)
>     {
>        DBSet<String>  result = allCustomer()
>           .select(#(c){c.getName()})
> //; result = result    // if you uncomment this line, then it compiles fine
>           .sortedByStringAscending(#(str){str});
>     }
> }
> But if I uncomment the 4th line from the bottom, it then compiles fine.
> -Ming

More information about the lambda-dev mailing list