Can you pass predetermined or optional arguments in Java as it is done in PHP?

2

I have a Java method where I sometimes need to use a numeric value, but sometimes I do not.

In PHP there is something called Default argument values , where you can do something like that ( example from the same PHP manual ):

<?php
function hacer_café($tipo = "capuchino")
{
    return "Hacer una taza de $tipo.\n";
}
echo hacer_café();
echo hacer_café(null);
echo hacer_café("espresso");
?>

Result:

Hacer una taza de capuchino.
Hacer una taza de .
Hacer una taza de espresso.

In Java I get an error:

public SpannableStringBuilder getSalmoCompleto(int hourIndex=0) {
    //Evaluar hourIndex y resto del código 
}

The idea is to be able to call the method so much:

getSalmoCompleto();

Like so:

getSalmoCompleto(n);

Where n is any number.

    
asked by A. Cedano 04.12.2018 в 14:25
source

2 answers

6

Java does not support Arguments options to date. But you can use the overload of methods where you define one without arguments and you send the default value to the one that accepts the argument:

public SpannableStringBuilder getSalmoCompleto() {
    getSalmoCompleto(0);
}
public SpannableStringBuilder getSalmoCompleto(int hourIndex) {
    //Evaluar hourIndex y resto del código 
}

And so you can execute the method as you wish:

getSalmoCompleto() // se envia 0 por defecto.
    
answered by 04.12.2018 / 14:30
source
3

Although @Einer's answer is correct, in java you can define a method to pass an array of some type disguised as an "uncertain number of parameters", which could be used to simulate optional parameters:

public void unMetodo(String ... argumentos){
    // argumentos es un vector de String
}

When this method is called, it is done this way:

...
unMetodo("Hola", null,"Mundo"); // Podría haber más parámetros String
...

With this call the method receives the vector arguments as {"hola",null,"Mundo"} ;

If instead of String were Object the data type, in theory you could pass arguments of any kind (and then cast them into the method)

Something like this:

/*
Parametros: String nombre, int edad, Date fechaDeNacimiento
*/
public void metodoConParametrosOpcioneales(Object ... params){
    //Defaults
    String nombre = "Natalia Natalia";
    int edad  = -1;
    Date = null;
    if(params.length > 0) nombre = (String) params[0];
    if(params.length > 1) edad = (int) params[1];
    if(params.length > 2) nombre = (Date) params[2];

    // Resto de la lógica del método  

} 

Then if you call us:

metodoConParametrosOpcioneales("Juan");

Within the method, only the name will be set and both age and date of birth will have the default value.

EDITION I

  

I do not fully understand what you mean by losing the checkup   of the type of data. As for the use, it's for something very specific   (raised in this question). Actually, it's for two types of cases,   in one I will call the method passing it an hourIndex argument and in others   I will call the method without any argument. In that sense, the response of   @Einer responds completely to that requirement.

  • In php there is no check of the data type of the parameters, if a function that has to receive a boolean to do something, receives a int it simply breaks at run time.
    In java, a method like the one proposed by @Einer, is checked at compile time, if you pass a int where you have to go a boolean , the program does not compile.
    The alternative that I am exposing works as php in that sense, you can call the function with any type of data and if it is the correct one it will give an exception in execution time.

  • With a specific case I wanted to say that it is not good to lose the data check and for that reason I would not use it throughout a system, in each one of the methods.

  • For the specific case that you mention, referring to the other question, the number of parameters is well defined as well as its type of data. So I would like @Einer.

  •   

    My question is, if in   a hypothetical case is necessary to pass in some cases 1 argument, in   another 2 arguments, in another N arguments, if it is better this resp.

  • When the number of arguments is not fixed, wanting to emulate with a method like php works, in my opinion, this answer would be more accurate.
  • answered by 04.12.2018 в 15:40