2

I am trying to create a timer to print out from an ArrayList at a schedule. But I am receiving this error:

Cannot resolve method 'schedule(<lambda expression>,int,java.util.concurret.TimeUnit)'

Why am I receiving this error and what can I do about it?

List<String> finalQuestionsList = questionsList;
timer.schedule(()-> finalQuestionsList.forEach(write::println),120, TimeUnit.SECONDS); 
Josef Lundström
  • 197
  • 2
  • 15
  • Check out the different signature of the method `schedule` and make sure to comply with one of them: https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html – Nir Alfasi Apr 07 '17 at 17:00
  • 1
    `TimerTask` is not a functional interface, but you shouldn’t use that class anyway. Use a `ScheduledThreadPoolExecutor`… – Holger Apr 07 '17 at 17:52

1 Answers1

3

JLS asserts type of a lambda expression:

A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

  1. TimerTask is not a Function Interface, so you can't assign a lambda expression to a TimerTask. but you can adaptee a Runnable to a TimerTask with an adapter method task.

  2. Timer.schedule methods can't take a TimeUnit, but you can using TimeUnit.toMills() to convert a duration to milliseconds.

  3. I can't see any write variable in your code snippet, so I use System.out instead.

    List<String> finalQuestionsList = questionsList;
    timer.schedule(task(() -> finalQuestionsList.forEach(System.out::println))
             , 120, TimeUnit.SECONDS.toMillis(1));
    
    private TimerTask task(Runnable task) {
        return new TimerTask() {
          @Override
          public void run() {
            task.run();
          }
        };
    }
    
holi-java
  • 29,655
  • 7
  • 72
  • 83