How to write Java function that returns values of multiple data types?

后端 未结 11 1557
耶瑟儿~
耶瑟儿~ 2021-01-03 23:34

For example, I want to create a function that can return any number (negative, zero, or positive).

However, based on certain exceptions, I\'d like the function to re

11条回答
  •  隐瞒了意图╮
    2021-01-04 00:10

    no. the best you can do is return on instance of a class that handles all the things you might want to return.

    something like

    public class ReturnObj {
       public bool yesno; // yes or no
       public int val; // for int values
       public String mode; // mode describing what you returned, which the caller will need to understand.
    }
    

    obviously, you need to play with the names....

    Also, this seems like a code smell. You might be able to remove the need to do something like this by qualifying what path you want outside of your function, and then call a specific function to get a boolean or a specific function to get an int, depending on the qualification.

提交回复
热议问题