Search code examples
javafunctional-programmingrunnable

Functional programming syntax in Java


I was reading about Functional Programming and its implementation in Java. I came across this example which has some different syntax than Object Oriented Programming in Java. Is it that functional programming has some different syntax?

public class Hello {
    Runnable r1 = ()->(System.out.println(this);};
    Runnable r2 = ()->(System.out.println(toString());};
    public String toString(){ return “Howdy!”;}
    public static void main(String args) {
        new Hello().r1.run();
        new Hello().r2.run();
    }

After going through the code, I could understand that parenthesis is not matched properly, the syntax is not similar to Java syntax for OOP.

This code doesn't compile and gives following error on all the lines:

Hello.java:19: error: class, interface, or enum expected
Runnable r2 = ()->(System.out.println(toString());};

What is it that I am missing? If this program is correct, what shall it print? I am using javac 1.8.0_66 on Ubuntu 14.04.3

Thank you.


Solution

  • Your code has syntax errors. It should be :

    Runnable r1 = ()->{System.out.println(this);};
    Runnable r2 = ()->{System.out.println(toString());};
    

    Those are lambda expressions. This will also work :

    Runnable r1 = ()->System.out.println(this);
    Runnable r2 = ()->System.out.println(toString()); 
    

    This program will print Howdy twice, since that's what the toString method of your Hello class returns, and this inside a lambda expression refers to the instance in which the lambda expression is declared.