Vishwa Ratna
Vishwa Ratna

Reputation: 6390

Lambda body isn’t executed unless corresponding method is invoked

I am learning about Java Lambdas and I asked myself is it always required to call a abstract method of functional interface if I want to use the lambda here?

@FunctionalInterface
public interface A {
    public void somefunction();
}

@FunctionalInterface
public interface B extends A {

}

public class testing {
    public static void main(String[] args) {
        B b = () -> System.out.println("MyText");

        b.somefunction();   //Why do I need to call somefunction()
    }
}

If I don't write b.somefunction(); I don't get any output even though the compiler does not give an error.

I don't pass any value to the method so why do I need to call the abstract method?

Is there anyway to skip the abstract method call? If my case was to add or perform some calculations, then I can understand that I need to pass some values in method, but in the above scenario I am just printing the value.

Upvotes: 0

Views: 221

Answers (2)

erickson
erickson

Reputation: 269687

If you want the output to print when your program runs, write:

public class testing {
    public static void main(String[] args) {
        System.out.println("MyText");
    }
}

If you want the output to print when some other function runs, then you might use a lambda:

class Testing {
    public static void main(String[] args) {
        runn(() -> System.out.println("MyText"), 10);
    }
    static runn(Runnable task, int times) {
        for (int i = 0; i < times; ++i) {
            task.run();
        }
    }
}

Lambdas exist to make it easy to specify a function whose execution you want to delegate to another entity. When the lambda is invoked, its arguments, and the treatment of its result are up to someone else.

Upvotes: 3

glglgl
glglgl

Reputation: 91049

A functional interface serves to provide a way

  1. to define what is to be performed on a given call and
  2. to define when it is to be called.

Normally, you'd define a "lambda object" as you did and then pass it to somewhere else to tell what to do under a certain circumstance. If you want to see it this way, it is a kind of callback.

The entity where you pass this object calls/uses it when it sees time to do so, or you do it yourself, as you do it in your example.

Upvotes: 2

Related Questions