Java overload

When programming Haskell, I use the definition of the behavior of a function based on the input it receives, and not just its signature. For instance:

f :: Int -> Int
f 2 = 4
f 3 = 9
f 4 = 16
f x = 0

With Java, I know that I can overload a function as:

public String f (String s) {
    System.out.println(s);
}

public String fb (Integer i) {
    System.out.println("Sorry, not a string!");
}

However, I was wondering if I can overload a function based on its exact input, and not just on its signature. (To avoid case / if branches)

Sort of

public String f ("a") {
    /* do something */
}

public String f ("not a") {
    /* do something else */
}

Cheers, Dario

+4
source share
6 answers

Nope. This is not possible with Java. The best alternative is to use boxes, as you already mentioned.

+2
source

, public String f_a() public String f_not_a(), , Java , .

, , , .

: switch.

+1

oracle

, .

, .

, , .

+1

switch java :

public void tryMethod(String test)
{

     switch(test)
     {
           case "a" : //do something
                 break;
           case "b" : //do some other thing
                 break;

     }
}
+1

java si .

public interface ValueHolder {
    public String getValue();
}

public class A {
    String value;
    public A(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }
}

public class NotA {
    String value;
    public A(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }
}

:

public String f (A s) {
    System.out.println(s.getValue());
}

public String fb (NotA s) {
    System.out.println("Overloaded");
}

... switch:)

, switch ... case .

+1
source

Your example (if I understand it correctly, I don’t know, Haskell) is a "function" that does one-to-one matching of an integer with an integer with a limited set of values, mapped to the specified values ​​and all others mapped to 0. The closest analogy for Java in Java would have to use Map:

 private static final Map<Integer,Integer> mapping = new HashMap<>();
 static {
    mapping.put(2,4);
    mapping.put(3,9);
    mapping.put(4,16);
 }

 public int f(int x) {
    Integer result = mapping.get(x);
    if (result == null) {
       return 0;
    } else {
       return result;
    }
 }
+1
source

All Articles