How does Java functional programming return String to Supplier<String>?

created at 03-20-2022 views: 4

problem

When developing a project, use the following methods:

static void play(String target, Supplier<String> readGuess, Display display)

Its second parameter is method, and the method body uses readGuess.get() to call the second parameter to get the value.

static void play(String target, Supplier<String> readGuess, Display display) {
  // do something   
  var guess = readGuess.get();
  // do something 
}

The required return type is Supplier<String>, and I return String, what should I do?

public Supplier<String> readGuess() {
  waitForGuessButtonPressedLatch = new CountDownLatch(1);

  try {
    waitForGuessButtonPressedLatch.await();
  } catch (InterruptedException ignored) {}

  String guess = guessWord.toString();

  return guess.isEmpty() ? "" : guess;
}

solution

Just replace return string with return lambda expression.

public Supplier<String> readGuess() {
  waitForGuessButtonPressedLatch = new CountDownLatch(1);

  try {
    waitForGuessButtonPressedLatch.await();
  } catch (InterruptedException ignored) {}

  String guess = guessWord.toString();

  //return guess.isEmpty() ? "" : guess;
  return () -> guess;
}
created at:03-20-2022
edited at: 03-20-2022: