1

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Eran for the response. This was very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.