Path: csiph.com!news.redatomik.org!aioe.org!.POSTED!not-for-mail From: =?UTF-8?Q?Arne_Vajh=c3=b8j?= Newsgroups: comp.lang.java.programmer Subject: Re: Java 8 Lambda with generic types Date: Sun, 28 Aug 2016 07:46:20 -0400 Organization: Aioe.org NNTP Server Lines: 78 Message-ID: References: NNTP-Posting-Host: 7SK6yTFfqwlIPNBLl3l7Qg.user.gioia.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Thunderbird/45.2.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:35486 On 8/28/2016 3:02 AM, Stone Zhong wrote: > On Saturday, August 27, 2016 at 11:50:40 PM UTC-7, Stone Zhong wrote: >> It seems sometimes, the compiler is not smart enough to decide the >> generic parameter type based on labmda argument types, here is an example: >> >> I have a interface, say Toy: >> >> public interface Toy { >> List get(); >> } >> >> >> Now I have a method to process toys, such as: >> public static void checkToy(Toy toy) { >> } >> >> Now, the following code works >> checkToy(new Toy() { >> @Override >> public List get() { >> List ret = Arrays.asList(10); >> return ret; >> } >> }); >> >> However, if I have >> checkToy(() -> { >> return Arrays.asList(10); >> }); >> >> I got compiling error: "List cannot be converted to >> List", it seems compiler tried to create a instance of >> Toy instead of Toy based on the lambda. Is there a wait >> to tell the compiler it is Toy explicitly with the lambda >> expression? > > I just learned if I put all generic parameter in the method > parametereven if you do not use it, it helps the compiler to find the > right generic parameter type when instantiate the instance. > for example: > > public interface Toy { > List get(E dummy); > } > > did kind of solve the problem, but I do feel bit clumsy doing such thing. I think the problem really is in your checkToy method. The following works fine: import java.util.Arrays; import java.util.List; public class GenFun { public static interface Toy { public List get(); } public static void checkToy(Toy toy) { for(E o : toy.get()) { System.out.println(o); } } public static void main(String[] args) { checkToy(new Toy() { @Override public List get() { List ret = Arrays.asList(10); return ret; } }); checkToy(() -> { return Arrays.asList(10); }); } } Arne