theutonium.18
theutonium.18

Reputation: 525

When type arguments are supplied for the constructor - then Diamond Operator cannot be used and Type Arguments must be supplied?

Consider the following clause from the JLS (§15.9)

It is a compile-time error if a class instance creation expression provides type arguments to a constructor but uses the diamond form for type arguments to the class.

The reason why this is not allowed is given as the following

This rule is introduced because inference of a generic class's type arguments may influence the constraints on a generic constructor's type arguments.

Not very sure why this has been said so - consider the following typical usage of Type Parameters in the case of the generic class and the generic constructor:

class Scratch<T,R> {
  public <K> Scratch(K k, T t, R r){
  }

  public static void main(String[] args) {
    Scratch<Integer,Double> dd = new <String>Scratch<>("abdc",33,33.4); //compile error
  }
}

Here we have the following:

Then how is the above reason for "not allowing the diamond operator when Type arguments for the Constructor are being provided" valid?. Am I missing something here?

Upvotes: 0

Views: 63

Answers (0)

Related Questions