Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading in Java

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

like image 332
MrD Avatar asked Feb 13 '23 04:02

MrD


1 Answers

Nope. That is not possible with Java. Best alternative is using switch cases as you already mentioned.

like image 150
Varun Phadnis Avatar answered Feb 14 '23 17:02

Varun Phadnis