How does one method work within another? E.g: service.metodo(arguments). execute();

Asked

Viewed 92 times

4

I’m not understanding this method within another method someone explains it to me?

Another example of my doubt:

ImageKeywords keywords =  service.getImageKeywords(image, forceShowAll, knowledgeGraph).execute();

He has a method that calls another method within him.

1 answer

6


There is no method inside the other, there is a sequence of methods.

With the object servicecalls the method getImageKeywords() passing some arguments. It will produce a result (in general methods return something), this result is an object that can invoke other methods, in which case it is invoking the execute() on the object returned by getImageKeywords(). The result of execute() is that it will be stored in the variable keywords.

This code could be written like this (or almost, I used var, not yet available in Java, because I don’t know the type of method):

var temp = service.getImageKeywords(image, forceShowAll, knowledgeGraph);
ImageKeywords keywords = temp.execute();

Most visible example:

public static void main (String[] args) {
    String x = teste().toString(); //teste retorna um inteiro 42 que é usado pelo toString
    System.out.println(x); //x já é uma string "42"
}
public static Integer teste() {
    return 42;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

One thing that people don’t usually notice is that variables are used to hold intermediate values. There are cases where they are necessary, or at least more advantageous, but they do not always need to be used. An intermediate value of an expression can be used directly where necessary without the use of a variable.

An expression is usually composed of sub-expressions that produce intermediate values. Pure mathematics.

  • Got it! What a great example. But I got a question, @bigown, always have to return something to call another method?

  • 1

    Yes, and it is obvious that the following method will have to be available for the returned object. Can I improve the answer, do you have the context where this code is being used? Do you have the documentation for getImageKeywords?

  • No need, I got bored.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.