Skip to content

[java] Issue with type inference of nested lambdas #5324

@oowekyala

Description

@oowekyala

In the following UnusedPrivateMethod triggers, because type inference infers the wrong type for the result of Stream.map. So reduceBooksAndLenderStatusByLender doesn't apply because of argument type mismatch and is flagged as unused. This is a problem with core type resolution and is not specific to that rule.


Complete Maven project: https://github.com/lolo101/pmd-issue

package org.example.unusedPrivateMethod;

import static java.util.Collections.emptySet;

import java.util.*;
import java.util.stream.*;

public class Main {

    public static void main(String[] args) {
        Library library = new Library(emptySet());
        Map<String, Map<String, String>> map = new Main().run(library);
        System.out.println(map);
    }

    private Map<
        String,
        Map<String, String>
        > run(Library library) {
        return library
            .books()
            .stream()
            .map(
                book ->
                    book
                        .lenders()
                        .stream()
                        .collect(
                            Collectors.toMap(
                                Lender::name,
                                lender ->
                                    Map.of(
                                        book.title(),
                                        lender.status()
                                    )
                            )
                        )
            )
            .reduce(this::reduceBooksAndLenderStatusByLender)
            .orElse(null);
    }

    private Map<
        String,
        Map<String, String>
        > reduceBooksAndLenderStatusByLender(
        Map<String, Map<String, String>> previousMap,
        Map<String, Map<String, String>> nextMap
    ) {
        previousMap.putAll(nextMap);
        return previousMap;
    }
}

record Library(Collection<Book> books) {}
record Book(String title, Collection<Lender> lenders) {}
record Lender(String name, String status) {}

Originally posted by @lolo101 in #5184 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:bugPMD crashes or fails to analyse a file.in:type-resolutionAffects the type resolution code

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions