Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using Supplier in Java?

Tags:

java

java-8

Reading about the new Supplier interface I can't see any advantage of its usage. We can see bellow an example of it.

class Vehicle{
  public void drive(){ 
    System.out.println("Driving vehicle ...");
  }
}
class Car extends Vehicle{
  @Override
  public void drive(){
    System.out.println("Driving car...");
  }
}
public class SupplierDemo {   
  static void driveVehicle(Supplier<? extends Vehicle> supplier){
    Vehicle vehicle = supplier.get();
    vehicle.drive();   
  }
}
public static void main(String[] args) {
  //Using Lambda expression
  driveVehicle(()-> new Vehicle());
  driveVehicle(()-> new Car());
}

As we can see in that example, the driveVehicle method expects a Supplier as argument. Why don't we just change it to expect a Vehicle?

public class SupplierDemo {   
  static void driveVehicle(Vehicle vehicle){
    vehicle.drive();   
  }
}
public static void main(String[] args) {
  //Using Lambda expression
  driveVehicle(new Vehicle());
  driveVehicle(new Car());
}

What is the advantage of using Supplier?

EDIT: The answers on the question Java 8 Supplier & Consumer explanation for the layperson doesn't explain the benefits of using Supplier. There is a comment asking about it, but it wasn't answered.

What is the benefit of this rather than calling the method directly? Is it because the Supplier can act like an intermediary and hand off that "return" value?

like image 326
hbelmiro Avatar asked Nov 27 '15 15:11

hbelmiro


Video Answer


1 Answers

In your example above I'd not use a supplier. You are taking a Vehicle to drive, not requesting vehicles.

However to answer your general question:

  • Because building a car is expensive and we don't want to do it until we really really need to.
  • Because we want X cars not just one.
  • Because the time of construction for a car is important.
  • Because construction is complicated so we want to wrap it up.
  • Because we don't know which Vehicle to return until we return it (maybe it will be a new one, maybe a recycled one, maybe a wrapper, who knows)
like image 124
Michael Lloyd Lee mlk Avatar answered Sep 18 '22 20:09

Michael Lloyd Lee mlk