简体   繁体   中英

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.

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 (eg, 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.

In statically typed languages, like Java, there is usually a super type to which all other types belong. In java it is Object .

So you can directly convert your code to the following:

public static Object f(int a) {
    if (a > 11)
        return 200;
    else
        return "not valid";
}

However, this is considered bad programming. You should instead throw an exception in this case:

public static Object f(int a) throws IllegalArgumentException {
    if (a > 11)
        return 200;
    else
        throw new IllegalArgumentException("not valid");
}

In Java, exceptions are essentially "valid" outputs that can be thrown outside of normal operation. If not "caught" by the calling method, they will be thrown by the program executioner, and "elegantly crash" the application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM