# Use Functional Interfaces

# Properties

Property Value
Rule ID FunctionalInterface
First seen in jSparrow version 1.0.0
Minimum Java version 8
Remediation cost 5 min
Links S1604

# Description

Converts anonymous inner classes to equivalent lambda expressions.

# Benefits

Increases the performance, because lesser objects need to be created. Improves readability because a lot of boilerplate code will be removed.

# Code Changes

# Remove anonymous instantiation of functional interface

Pre

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("xx");
    }
};

Post

Runnable runnable = () -> {
    System.out.println("xx");
};

# Rename variables if they are present in the scope outside of the inner class

Pre

int a = 5;

AFunctionalInterface foo = new AFunctionalInterface() {
    @Override
    public void method(int a) {
        int b = a;
    }
};

Post

int a = 5;

AFunctionalInterface foo = (int a1) -> {
    int b = a1;
};

# Bytecode JDK 1.8

Pre

public Runnable runableWithAnonymousClass() {
    Runnable r = new Runnable() {
        public void run() {
            System.out.println("Anonymous class");
        }
    };
    return r;
}
 0 new #2 <at/splendit/AnonymousClassesToLambdaExpressions$1>
 3 dup
 4 aload_0
 5 invokespecial #3 <at/splendit/AnonymousClassesToLambdaExpressions$1.<init>>
 8 astore_1
 9 aload_1
10 areturn

Post

public Runnable runableWithLambda() {
    Runnable r = () -> {
            System.out.println("Lambda");
        };
    return r;
}
0 invokedynamic #4 <run, BootstrapMethods #0>
5 astore_1
6 aload_1
7 areturn


0 getstatic #5 <java/lang/System.out>
3 ldc #6 <Lambda>
5 invokevirtual #7 <java/io/PrintStream.println>
8 return

# Limitations

Variables that are used inside the anonymous class must be effectively final.

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊