Lambdas in Java 8 – Ex #1: functional set – Ex #2: Abstraction



Lambdas in Java 8 – Ex #1: functional set – Ex #2: Abstraction

0 0


it-rally-2014-05


On Github siryc / it-rally-2014-05

Lambdas in Java 8

sirycd@gmail.com

What is lambdas in Java 8

  • not only closures
  • not only syntactic sugar
  • It's a Functions!

Functional programming

  • functions as a first class cityzens
  • higher order functions
  • function composition

Ex #1: functional set

  • every set could be presented as a predicate
  • Set of integers greater than 0 can be expressed as
  • x > 0

Ex #1: functional set

interface Set extends Predicate<Integer>

Ex #1: functional set

interface Set extends Predicate<Integer>

boolean contains(Set s, int i) { return s.test(i); }

Ex #1: functional set

interface Set extends Predicate<Integer>

boolean contains(Set s, int i) { return s.test(i); }

Set union(Set s, Set t) { return x -> contains(s, x) || contains(t, x); }

Set intersect(Set s, Set t) {return x -> contains(s, x) && contains(t, x);}

Set diff(Set s, Set t) { return x -> contains(s, x) && !contains(t, x); }

Ex #1: functional set

Set positive = x -> x > 0;

Theory

  • Every function has a type: x -> y
  • Function that returns function: x -> y -> z
  • java.util.function.Function<T, R>: t -> r
  • java.util.function.Predicate<T>: t -> Boolean
  • java.util.function.Consumer<T>: t -> ()
  • java.util.function.Suplier<T>: () -> t

Ex #2: Abstraction

FileOutputStream file = new FileOutputStream("file.txt");

try {
  file.write("Hello from past!".getBytes());
catch (Exception e) {
  System.out.println("Something bad happened.");
  e.printStackTrace();
} finally {
  if (file != null) {
    try {
	  file.close();
    } catch (Exception e) {}
  }
}

Ex #2: Abstraction

try (FileOutputStream file = new FileOutputStream("file.txt")) {
	file.write("Hello from present!".getBytes());
} catch (Exception e) {
	System.out.println("Something bad happened.");
    e.printStackTrace();
}

Ex #2: Abstraction

withResource(new FileOutputStream("file.txt"))
.perform(r -> r.write("Hello from better present!".getBytes()));

Ex #2: Abstraction

public class Resources {
	public static  <R> Action<R> withResource(final R r) {
		return new Action<R>() {
            @Override
            public void perform(Consumer<R> consumer) {
                try (AutoCloseable a = (AutoCloseable) r) {
                    R res = (R) a;
                    consumer.accept(res);
                } catch (Exception e) {
                    System.out.println("Something bad happened.");
                }
            }
        };
	}
    public static interface Consumer<T> {
        void accept(T t) throws Exception;
    }
    public static interface Action<T> {
        void perform (Consumer<T> consumer);
    }
}

Implementation

public class Main {
    public static void main(String [] args) {
        Predicate<Integer> p = x -> x > 0;
        boolean res = p.test(1);
        System.out.println(res);
    }
}
						

Implementation

javap -c Main
public static void main(java.lang.String[]);
    Code:
       0: invokedynamic #2,  0              // InvokeDynamic #0:test:()Ljava/util/function/Predicate;
       5: astore_1      
       6: aload_1       
       7: iconst_1      
       8: invokestatic  #3                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      11: invokeinterface #4,  2            // InterfaceMethod java/util/function/Predicate.test:(Ljava/lang/Object;)Z
      16: istore_2      
      17: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
      20: iload_2       
      21: invokevirtual #6                  // Method java/io/PrintStream.println:(Z)V
      24: return

Implementation

javap -p -c Main
private static boolean lambda$main$0(java.lang.Integer);
    Code:
       0: aload_0       
       1: invokevirtual #7                  // Method java/lang/Integer.intValue:()I
       4: ifle          11
       7: iconst_1      
       8: goto          12
      11: iconst_0      
      12: ireturn

Methods are functions

public class Main2 {
    public static void main(String [] args) {
        doTest(x -> x > 0, 7);
        doTest(Main2::test, 0);
    }

    public static boolean doTest(Predicate<Integer> p, int i) {
        return p.test(i);
    }

    static boolean test(Integer x) { return x > 0; }
}
						

Methods are functions

							boolean test(Integer x) { return x > 0; }
						

Has type: Integer -> Boolean

Results

  • New ways for abstraction and compostiotion
  • More power - more responsibility
  • Experience comes with a practice

More fun

How to use?

“Don’t think, feel! It is like a finger pointing away to the moon. Don’t concentrate on the finger or you will miss all that heavenly glory.”

- Bruce Lee

Thank You!