Search code examples
javapythonreturn-type

How to replicate in statically typed language?


You don't have to declare return type in Python but in other languages like Java you have to specify beforehand. So how can we write below program in a statically typed language? Return type depends on whether condition is true or not.

def f(a):
    if a > 11:
        return 200
    else:
        return "not valid"

If condition is true, return type is int. If not it is string.


Solution

  • In Java or any other language that supports exceptions, you would raise an exception. That is what exceptions are for:

    int f (int a) {
        if (a > 11) return 200;
        throw new Exception();
    }
    

    In a language that does not support exceptions (e.g., C), you would return a sentinel: a value that cannot possibly be a real response:

    int f (int a) {
        if (a > 11) return 200;
        return -1; // Or 0, or any other invalid number
    }
    

    Some languages (Rust, Erlang) allow you to return tuples. You can use the first element of a tuple as the status (error/success) and the second as the actual return value in case of success.