Skip to content

ReplaceStreamCollectWithToList creating incompatible types #791

@protocol7

Description

@protocol7

What version of OpenRewrite are you using?

  • org.openrewrite:rewrite-core:8.56.1
  • org.openrewrite.recipe:rewrite-migrate-java:3.12.0

What is the smallest, simplest way to reproduce the problem?

When a super type is used in a Stream, relative to the expected return type, ReplaceStreamCollectWithToList should not replace collect(toUnmodifiableList()) or collect(toList()).

  @Test
  public void toUnmodifiableListOfSuperType() {
    rewriteRun(
        spec -> spec.recipe(new ReplaceStreamCollectWithToList(false)),
        java(
            """
            package com.helloworld;

            import java.util.stream.Collectors;
            import java.util.stream.Stream;
            import java.util.List;

            public static class Foo {
              public List<Number> foo() {
                return Stream.of(Integer.valueOf(1)).collect(Collectors.toUnmodifiableList());
              }
            }
            """,
            s -> s.markers(new JavaVersion(randomId(), "", "", "21", "21"))));
  }
org.opentest4j.AssertionFailedError: [Expected recipe to complete in 0 cycles, but took at least one more cycle. Between the last two executed cycles there were changes to "com/helloworld/Foo.java"]
expected:
  "package com.helloworld;

  import java.util.stream.Collectors;
  import java.util.stream.Stream;
  import java.util.List;

  public static class Foo {
    public List<Number> foo() {
      return Stream.of(Integer.valueOf(1)).collect(Collectors.toUnmodifiableList());
    }
  }"
 but was:
  "package com.helloworld;

  import java.util.stream.Stream;
  import java.util.List;

  public static class Foo {
    public List<Number> foo() {
      return Stream.of(Integer.valueOf(1)).toList();
    }
  }"
	at org.openrewrite.test.LargeSourceSetCheckingExpectedCycles.afterCycle(LargeSourceSetCheckingExpectedCycles.java:97)
	at org.openrewrite.RecipeScheduler.runRecipeCycles(RecipeScheduler.java:95)
	at org.openrewrite.RecipeScheduler.scheduleRun(RecipeScheduler.java:41)
	at org.openrewrite.Recipe.run(Recipe.java:441)
	at org.openrewrite.test.RewriteTest.rewriteRun(RewriteTest.java:377)
	at org.openrewrite.test.RewriteTest.rewriteRun(RewriteTest.java:130)

This creates code that will fail to compile: error: incompatible types: List<Integer> cannot be converted to List<Number>.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions