When programming Haskell, I am used to defining the behavior of a function based on the input it receives, and not just its signature. For example:
f :: Int -> Int
f 2 = 4
f 3 = 9
f 4 = 16
f x = 0
With Java, I know 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 could overload a function based on its exact input, rather than just its signature. (To avoid case/if branches)
Something like
public String f ("a") {
/* do something */
}
public String f ("not a") {
/* do something else */
}
Cheers, Dario
Nope. That is not possible with Java. Best alternative is using switch cases as you already mentioned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With