Generics type inference fails?

后端 未结 2 1378
别跟我提以往
别跟我提以往 2021-01-02 11:41

Example A

Study the following snippet:

public class ExampleA {
   static class Pair { }

   static  Pair anyPair()         


        
2条回答
  •  情话喂你
    2021-01-02 12:14

    Your second call to anyPair() does not have any way to determine it's types and so it defaults to .

    The compiler is breaking process(p, anyPair()); into it's pieces and processing each individually. When it does this, it needs to process the arguments first to determine their types, which can then be used when processing process.

    When it goes to process anyPair() there is no type information available for that piece, because it does not know that it is part of process at that point. It defaults to , which then causes a type mismatch when looking at process.

    The same thing happens with your second example. Collections.emptySet() needs to be processed by itself, but has no way of determining the Types needed.

    There are 2 ways to solve this:

    The first is to give the compiler the information it needs for type inference the same way you did with the first call to anyPair(), by storing it in a temporary variable with the correct type.

    The second (thanks to @BalusC) is to use ExampleA.anyPair(). This syntax explicitly sets the types needed without having to look beyond the invocation.

提交回复
热议问题