Type inference of parameters

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Jul 15 10:42:54 PDT 2010


On 15/07/10 16:40, Kieron.Wilkinson at paretopartners.com wrote:
> Brian Goetz wrote on 07/07/2010 19:18:14:
>    
>> Yes.  I, for one, am in favor of type inference :)
>>
>> Type inference is a key underlying motivator for a number of JDK 7
>>      
> language
>    
>> changes, including lambda and diamond.  We are all about static typing,
>>      
> but
>    
>> that doesn't mean that the user has to laboriously write out every
>> single type
>> declaration when it is obvious from the context.
>>      
> This is a really exciting (and unexpected) development. I definitely vote
> for this!
>
> I'd be interested to know how far this goes (or how far it is intended to
> go). Will it be able to infer the types from generic parameters like Scala
> does? For example, given a "map" method defined in a List<A>  class:
>
>    public<B>  List<B>  map(Function<A, B>  function);
>
> Could I write something like the following?
>
>    List<Animal>  animals = ...
>    List<Food>  foods = animals.map({ a ->  a.getFood() });
>
> Rather than:
>
>    List<Food>  foods = animals.map({ Animal a ->  a.getFood() });
>
> ?
>
> We use our own collection library that has Function-like classes used for
> fold/map/etc, and it would be great if we didn't have to put in type
> annotations where they are obvious (especially helpful with multiple
> parameters or long class names).
>
> Thanks,
> Kieron
>
>    
Hi Kieron
I'm glad to know that you like the way things are shaping out; I'm also 
glad to tell you that your example should work with the current 
inference scheme and that removing 'obvious' type annotation is one of 
the goals of the new proposal!

More specifically, in your example, the compiler instantiates the 
unknown lambda argument type to the element type of the list upon which 
the 'map' method is being called (hence the type of 'a' is Animal); the 
type-variable 'B' will be inferred from the assignment context (hence B 
== Food).

Maurizio
> This message may contain confidential and privileged information and is intended solely for the use of the named addressee. Access, copying or re-use of the e-mail or any information contained therein by any other person is not authorised. If you are not the intended recipient please notify us immediately by returning the e-mail to the originator and then immediately delete this message. Although we attempt to sweep e-mail and attachments for viruses, we do not guarantee that either are virus-free and accept no liability for any damage sustained as a result of viruses.
>
> Please refer to http://www.bnymellon.com/disclaimer/piml.html for certain disclosures.
>
>    



More information about the lambda-dev mailing list