netbeans icon indicating copy to clipboard operation
netbeans copied to clipboard

Extracting lambda expression - without {} - to a new method creates valid java code

Open Honza-cz opened this issue 2 years ago • 0 comments

resolves https://github.com/apache/netbeans/issues/6311

Fixes the issue linked to extracting parameterized lambda into a method. I tested manually all cases I have in mind. The fix itself is not nicest, but it works. I was unable to write meaningful automated tests for that class.

source code:

public class ExtractMethodDemo11 {
    
    public static void main(String[] args) {
        String unused = "unused";
        String first = "hello";
        String second = "world";

        System.out.println(
                java.util.Optional.ofNullable("-")
                        .map(t -> first + t + second)
                        .orElseThrow()
        );
    }
}

extracting first + t + second:

public class ExtractMethodDemo11 {
    
    public static void main(String[] args) {
        String unused = "unused";
        String first = "hello";
        String second = "world";

        System.out.println(java.util.Optional.ofNullable("-")
                        .map(t -> inner(first, t, second))
                        .orElseThrow()
        );
    }

    private static String inner(String first, String t, String second) {
        return first + t + second;
    }
}

extracting t -> first + t + second:

public class ExtractMethodDemo11 {
   
    public static void main(String[] args) {
        String unused = "unused";
        String first = "hello";
        String second = "world";

        System.out.println(java.util.Optional.ofNullable("-")
                        .map(inner(first, second))
                        .orElseThrow()
        );
    }

    private static Function<String, String> inner(String first, String second) {
        return t -> first + t + second;
    }
}

As I mentioned in bug, lambda with {} still cannot be extracted correctly to a method. The problem is with return type of the newly created method which is taken not from lambda, but from enclosing method. I was not able to resolve this issue yet.

Honza-cz avatar Oct 19 '23 20:10 Honza-cz