0

I'm trying to simplify my object creation with lamdas.

I have a class that provides the public void addCmd(ScriptCommand cmd)-method.

With this I can write a call like this:

ScriptCommand cmd = new ScriptCommand() {
                    @Override
                    public void run(double deltaTime) {
                      // some logic here...
                    }
                };
addCmd(cmd);

I've already tried to call something like this:

ScriptCommand cmd = (deltaTime) -> {
                    // some logic here...
                };
addCmd(cmd);

However, this is recognized as an error by the IDE. How do you use lambdas in such a case?

EDIT:

ScriptCommand looks like that:

public abstract class ScriptCommand {
    private boolean completed = false;

    public abstract void run(double deltaTime);

    protected void complete() {
        completed = true;
    }

    public boolean isCompleted() {
        return completed;
    }

}
EchtFettigerKeks
  • 1,692
  • 1
  • 18
  • 33
  • 3
    What is `ScriptCommand`? My guess is that it's not a functional interface. You can only write lambdas with functional interfaces (interfaces with only one method) because otherwise the compiler wouldn't know which method you are trying to implement, and you would end up with unimplemented methods. – Charlie Armstrong Mar 30 '21 at 17:52
  • 1
    @CharlieArmstrong: *"(interfaces with only one method)"* ... A *functional interface* may actually have any number of method declarations (several of the functional interfaces in the Java Platform Libraries add helper methods, for example). However, the stipulation that must be true is that a functional interface -must- have one (and only one) abstract method. – scottb Mar 30 '21 at 18:10
  • @scottb Good point, I should have said "only one *abstract* method." – Charlie Armstrong Mar 30 '21 at 19:09
  • hey @CharlieArmstrong and scottb, I've just edit my post and add the structure for ScriptCommand.java. Can you tell me what I should change/add in best practice? – EchtFettigerKeks Mar 30 '21 at 19:58
  • @MarcM - Study [this](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach5) thouroghly. – Arvind Kumar Avinash Mar 30 '21 at 20:11
  • 1
    @MarcM You can't have `ScriptCommand` be both a class and an interface. Interfaces can't have fields (other than constants), so if you need the `completed` field, you're gonna need to either store it in another class, or stick with an abstract class. – Charlie Armstrong Mar 30 '21 at 20:16

1 Answers1

0

Example:

@FunctionalInterface // Optional
interface ScriptCommand {
  void run(double deltaTime);
}

public static void main(String[] args) {
  ScriptCommand command = (deltaTime) -> System.out.println(deltaTime);
  // execute code
  command.run(3);
  // if you want to call addCmd(ScriptCommand)
  addCmd(command);
  addCmd((deltaTime) -> System.out.println(deltaTime));
}

Output: 3.0

Akif Hadziabdic
  • 2,692
  • 1
  • 14
  • 25