0

I'm interested in understanding why, in the example given below, the row instantiating wrapper2 gives a compilation error:

java: incompatible types: inference variable V has incompatible bounds
    equality constraints: java.util.stream.Stream<EntityVersion<? extends BaseEntity>>
    lower bounds: java.util.stream.Stream<EntityVersion<Product>>

Example:

import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.val;

@Data
class BaseEntity {
    UUID id;
}

@Data
@AllArgsConstructor
class Product extends BaseEntity {
    String name;
};

@Data
@AllArgsConstructor
class EntityVersion<T extends BaseEntity> {
    String status;
    T entity;
}

record EntityVersions(Map<String, Stream<EntityVersion<? extends BaseEntity>>> entityVersions) {}

class Main {
    
    public static void main(String[]args){
        EntityVersion<Product> product = new EntityVersion<>("new", new Product("Product 1"));
                
        Stream<EntityVersion<? extends BaseEntity>> products1 = Stream.of(product);
        val wrapper1 = new EntityVersions(Map.of("products", products1));
        
        Stream<EntityVersion<Product>> products2 = Stream.of(product);
        val wrapper2 = new EntityVersions(Map.of("products", products2));
    }
}


Francesco Papagno
  • 617
  • 10
  • 29
  • 2
    A `List` is not a `List` and a `Stream>` is not a `Stream>`. But there’s no sense in storing a Stream anyway. – Holger Feb 27 '23 at 13:59
  • 1
    Even though `EntityVersion` is a subtype of `EntityVersion extends BaseEntity>`, that does not mean `Stream>` is a subtype of `Stream>`, in the same way that `Stream` is not a subtype of `Stream`. See also [this recent question I answered](https://stackoverflow.com/q/75332666/5133585), which is also about the subtyping of nested generics. They follow the same rules as a single layer of generics, really. – Sweeper Feb 27 '23 at 14:04
  • 1
    Rather, `Stream>` is a subtype of `Stream extends EntityVersion extends BaseEntity>>`. – Sweeper Feb 27 '23 at 14:06

0 Answers0