#Java Callback

1 messages · Page 1 of 1 (latest)

scenic zephyr
#

Hi there, I am coding a little Java stuff for my school, and I can't seem to find anything online to help. I want to use a callback function as sort of rich-code (we do not need to do it) because i repeat loops a bunch. I want to sort of reference or callback this function or set of commands again time after time. Something like in the callback of Javascript if that helps. Thanks!

ember hawkBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

the traditional way). Can you please explain how to use callback functions in Java?

wise kelp
#

Mind posting some psudo code to better explain what you mean?

shut verge
#

taking an argument whose type is a Functional Interface is the modern convention in Java.

#
public void someMethod(String foo, IntSupplier callback) {
   ...
   int v = callback.getAsInt();
}

Here I've used IntSupplier as the type of the callback. This interface provides an int getAsInt() method.

it could be called using a lambda or a method reference.

String s = "abc";
String t = "Some other String";

someMethod(s, () -> t.length());
someMethod(s, t::length);
ember hawkBOT
#

@scenic zephyr

Your question has been closed due to inactivity.

If it was not resolved yet, feel free to just post a message below
to reopen it, or create a new thread.

Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.

When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.

Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.

With enough info, someone knows the answer for sure 👍

scenic zephyr
shut verge
#

I'm not sure what callbacks have to do with repeating moves. Are you just wanting to repeating those loops? That's just a regular method.

private static void setAndMove(Googa g, int x, int y) {
   g.setPosition(x, y);
   for (int i = 0; i < 5; i++) {
       g.turnRight();
       g.move();
   }
}

...

Googa g = new Gogga();
setAndMove(g, 1, 1);
setAndMove(g, 9, 1);
setAndMove(g, 9, 9);
setAndMove(g, 1, 9);
#

Far more interesting would be a Move interface that can compose some base operations.

#

Note: this ignores defensive copies and bounds checks and is formatted for brevity.

interface Gogga {
    void move();
    void turnLeft();
    void turnRight();
}

@FunctionalInterface interface Action {
    public static Action repeat(Action action, int count) {
        return g -> {
            for (int i = 0; i < count; i++) { action.run(g); }
        };
    }

    public static Action of(Action... actions) {
        return g -> {
            for (Action action : actions) { action.run(g); }
        };
    }

    void run(Gogga g);
}

enum StandardAction implements Action {
    MOVE() { @Override public void run(Gogga g) { g.move(); } },
    TURN_LEFT() { @Override public void run(Gogga g) { g.turnLeft(); } },
    TURN_RIGHT() { @Override public void run(Gogga g) { g.turnRight(); } };
}

class GoggaTest implements Gogga {
    @Override public void move() { System.out.println("Move"); }
    @Override public void turnLeft() { System.out.println("Left"); }
    @Override public void turnRight() { System.out.println("Right"); }
}

...

var test = new GoggaTest();
var action = Action.of(Action.repeat(Action.of(StandardAction.TURN_RIGHT, StandardAction.MOVE), 3), StandardAction.TURN_LEFT);

action.run(test);

Prints something like...

Right
Move
Right
Move
Right
Move
Left
scenic zephyr
#

I dont want to have some really messy code thats just a bunch of repeats, id much rather just like callback to something and the code does it for me yk?

#

and i really dont know much about what is written there xd

#

could you explain? briefly so you dont have to like say paragraphs, i feel bad xd

#

i dont want to copy code yk, i want to learn it so i can put it to use and during like a test i i can save time, im not trying to do this to get marks, all the stuff we do i know already lol, just tryna do some extra cause im interested in learning java too

shut verge
#

How is a 'callback' different from the method approach? What are you trying to achieve that would make a callback useful?

scenic zephyr
#

i wanna use less lines of code, because it gets really messy

wise kelp
#

I think you're asking how you can split your code up into methods and re-use them, callbacks is something else

#

talden is right in his example and in the screenshot you provided, you're repeating code that you want to avoid

#

so if you take his example, he's created a method that does your repeated looping logic

#
private static void setAndMove(Googa g, int x, int y) {
   g.setPosition(x, y);
   for (int i = 0; i < 5; i++) {
       g.turnRight();
       g.move();
   }
}
``` (the code he provided)
#

now in your screenshot, all the code that has this ```java
g.setPosition(x, y);
for (int i = 0; i < 5; i++) {
g.turnRight();
g.move();
}

#

can be replaced with simply, setAndMove(g, 1, 1); (update the values as needed)

#

If you're struggling to understand this code, it might be worth doing some research into methods/functions in java

scenic zephyr
#

oh, i guess im being stupid, i thought callbacks were the same in java script xd

#

thank youuu

#

sorry for being so hard to work with xd

wise kelp
#

they should be the same but even in javascript, they're different to what you're asking here lol