Question

I stumbled upon this error today and I don't completely understand what the problem is.

I have a simple interface

public interface MyInterface
{
}

I then try to create a Guava ImmutableSet using the of() method passing it an anonymous class instance.

ImmutableSet<MyInterface> a = ImmutableSet.of(new MyInterface()
{
});

The compiler doesn't like it:

Type mismatch: cannot convert from ImmutableSet<new MyInterface(){}> to ImmutableSet<MyInterface>

What kind of type is ImmutableSet<new MyInterface(){}>? I am not familiar with this syntax.

Was it helpful?

Solution

This was part of the type inference feature improvement in Java 8, where it works. In Java 8, the type argument can be inferred from the context where the expression is used. Here it is being used in an assignment expression to a ImmutableSet<MyInterface> variable.

This was not true in Java 7.

In Java 7, you can do

ImmutableSet<MyInterface> a = ImmutableSet.<MyInterface>of(new MyInterface() {
});

to explicitly set the type argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top