Java Generics Incompatible Types (No Instance(S) of Type Variable(S) Exist)

Java generics incompatible types (no instance(s) of type variable(s) T exist)

Minimize your example like (using Integer of the templated List type):

class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
List<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> inRange = Helper.inRange(list, 0,1);
}
}

class Helper {
public static <T> List<T> inRange(List<T> list, int index, int range) {
List<T> res = new ArrayList<T>();
return res;
}
}

Then even if you put template types out of the picture:

ArrayList inRange = Helper.inRange(list, 0,1);

public static List inRange(List list, int index, int range) { ... }

you see that while the helper static method returns a List, you are trying to assign it to an ArrayList, and that's your problem, as ArrayList is a concrete implementation of List, but you cannot assign a reference to a generic List to a concrete implementation of ArrayList

Just change to:

List<View> inRange = Helper.inRange(gameView.activePlayersViews(), pos, 
playerView.range());

and you are good to go: https://ideone.com/MXZxqz

Java error: incompatible types: no instance(s) of type variable(s) T exist so that Optional<T> conforms to Iterable<AvailableLicence>

I would spare the caller of runWithRetry() having to handle the checked InterruptedException. For example like this

public static <T> Optional<T> runWithRetry(final Supplier<T> t, int retryAttempts, long retryDelayInMilliseconds) {

return handleSleep(t, retryAttempts, retryDelayInMilliseconds);
}

private static <T> Optional<T> handleSleep(final Supplier<T> t, int retryAttempts, long retryDelayInMilliseconds){

Optional<T> retVal = Optional.empty();

for(int retry = retryAttempts; retry >= 0; retry--) {
try{
retVal = Optional.of(t.get());
}
catch(Exception e) {
if(retry == 0) {
throw e;
} else if (retryDelayInMilliseconds > 0) {
try{
Thread.sleep(retryDelayInMilliseconds);
} catch(InterruptedException ie){ /*TODO: Handle or log warning */ }
}
}
}
return retVal;
}

See how I used that in my demo

...
Optional<Iterable<AvailableLicense>> licenses = Deduper.runWithRetry( ()->

{ return licensor.findAvailableLicenses(licenseOptions); }, 3, 5000 );

licenses.ifPresent(out::println);
...

Because I've implemented AvailableLicense.toString(), my demo outputs…

[AvailableLicense[ type: To Kill!]]

Optional - The Mother of all Bikesheds from @StuartMarks — one of the Oracle core devs that implemented Optional is recommended viewing for everybody using Optional.

Java generics incompatible types (no instance(s) of type variable(s) exist)

You are streaming entries from the map:

sCPairsObject.setSCPairs(util.getSCMap().entrySet().stream()

Then filtering out some of them:

.filter(entry -> entry.getValue().contains("abc"))

now you need to map the entries to List, for example:

.map(entry -> entry.getValue())

and stream the contents of all these lists as one stream:

.flatMap(List::stream)

Finally collect the values into a list:

.collect(Collectors.toList());

incompatible types: no instance(s) of type variable(s) F,T exist so that java.util.Collection<T> conforms to java.util.Set<java.lang.Long

There's no reason to expect that the result of Collections2.transform, which is a Collection, will be magically transformed to a Set. This is the reason for the type matching error in the title. You'll need either to convert the result to a set explicitly or make do with the Collection.

Since you're already using Guava, you should strongly consider ImmutableSet, so it's

ImmutableSet<Long> ids 
= ImmutableSet.copyOf(Collections2.transform(getComplexItems(), item -> item.id)));

Taking a step back, remember Guava was created before Java Streams. It's generally preferable to use language built-ins rather than a third party library, even when it's as good as Guava. In other words, prefer

getComplextItems().stream().map(item -> item.id).collect(toImmutableSet());

where toImmutableSet() is a collector defined by ImmutableSet.

No instance(s) of type variable(s) U exist so that void conforms to U

Optional.map() expects a Function<? super T, ? extends U> as parameter. Since your method returns void, it cannot be used like this in the lambda.

I see three options here:

  • make that method return Void/Object/whatever instead – semantically not ideal but it would work
  • make that method return the exception, and change the lambda definition to
    .map(v -> {
    throw printAndReturnException();
    });
  • use ifPresent(), and move the orElseThrow() outside of the call chain:
    values.stream()
    .filter(value -> getDetails(value).getName.equals("TestVal"))
    .findFirst()
    .ifPresent(value -> printAndThrowException(value))
    throw new Exception2("xyz");

No instance(s) of type variable(s) T exist so that List<T> conforms to Integer

The fundamental problem is that a different (unwanted) overloaded version of the "query" method is inferred (based on the code) and the lambda (Function) given as third parameter is not appropriate for this version of "query".

A way to fix this is to "force" the query function you want by providing the type parameter as such:

return new HashSet<>(namedParameterJdbcTemplate.<BigDecimal>query( ...

No instance(s) of type variable(s) U exist so that Optional<U> conforms to Response

Based on the error, the return type of your method is Response. However, update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build()) returns an Optional<U>, so you have to change the return type to Optional<Response>.

So the method would look like this:

public Optional<Response> yourMethod (...) {
return update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build());
}

Or, if you don't want to change the return type, add an orElse call, to specify a default value:

public Response yourMethod (...) {
return update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build()).orElse(defaultValue);
}


Related Topics



Leave a reply



Submit