Collections.emptyList() returns a List<Object>?

前端 未结 4 777
轮回少年
轮回少年 2020-12-02 04:23

I\'m having some trouble navigating Java\'s rule for inferring generic type parameters. Consider the following class, which has an optional list parameter:

im         


        
4条回答
  •  情歌与酒
    2020-12-02 04:48

    Since Java 8 this kind code compiles as expected and the type parameter gets inferred by the compiler.

    public Person(String name) {
        this(name, Collections.emptyList()); // Compiles fine in Java 8
    }
    
    public Person(String name, List nicknames) {
        this.name = name;
        this.nicknames = nicknames;
    }
    

    The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only direct assignments and arguments to methods where used for type parameter inference.

    In this case the parameter type of the constructor will be the target type for Collections.emptyList(), and the return value type will get chosen to match the parameter type.

    This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.

    Java is getting closer to proper Hindley–Milner type inference for every release!

提交回复
热议问题