Skip to content

ReplaceLambdaWithMethodReference converts a BiPredicate lambda to a single-arg Predicate method reference #900

@protocol7

Description

@protocol7

What version of OpenRewrite are you using?

  • rewrite-static-analysis 2.34.1
  • rewrite-core 8.81.7
  • rewrite-java 8.81.7

How are you running OpenRewrite?

Via a custom recipe list that includes org.openrewrite.staticanalysis.ReplaceLambdaWithMethodReference.

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

ReplaceLambdaWithMethodReference converts a two-argument BiPredicate lambda into a
single-argument method reference. When the lambda is (r, t) -> t instanceof X, the
recipe rewrites it to X.class::isInstance. But X.class::isInstance is a one-argument
Predicate, not a two-argument BiPredicate, so the result does not compile. The recipe
ignores the lambda's first parameter and only considers the parameter used in the
instanceof check.

package com.helloworld;

import java.util.function.BiPredicate;

public class Main {
  BiPredicate<String, Throwable> pred =
      (r, t) -> t instanceof IllegalArgumentException;
}

What did you expect to see?

No change. The lambda has two parameters (r, t) and only one of them is used in the
instanceof test, so it cannot be expressed as a method reference. IllegalArgumentException.class::isInstance
is a Predicate<Object> (single argument) and is not assignable to
BiPredicate<String, Throwable>.

What did you see instead?

The lambda was converted to:

BiPredicate<String, Throwable> pred = IllegalArgumentException.class::isInstance;

which fails to compile, because Class::isInstance is a unary functional reference and
the target type is a binary BiPredicate.

What is the full stack trace of any errors?

No stack trace from the recipe itself (it applies cleanly); the failure surfaces as a
downstream Java compilation error after the rewrite is applied. The compiler reports that
the method reference is not compatible with the BiPredicate functional interface
(incompatible parameter arity).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions