简体   繁体   中英

define variable with optional class type in if else statement

I need to change the class / stream type depending on whether a param (opath) is set, but when I declare in an if-else statement, netbeans complains that the variable oos cannot be found.

I don't understand this as the var oos is always set and there's no way that it is ever undefined ??

if(_param.get("opath") != null) {
    FileOutputStream oos = new FileOutputStream(_param.get("opath").toString());
} else {
    OutputStream oos = csocket.getOutputStream();
}

do something with oos...

Change you code to following

OutputStream oos;    
if(_param.get("opath") != null) {
    oos = new FileOutputStream(_param.get("opath").toString());
} else {
    oos = csocket.getOutputStream();
}
//do something with oos

It is just about scope and making the object available to the code where you want to use it

local varibales's scope is limited it's definition block, in this case, the if or else block, so it's unaccessible from outside.

you can move it out:

OutputStream oos;

if(_param.get("opath") != null) {
    oos = new FileOutputStream(_param.get("opath").toString());
} else {
    oos = csocket.getOutputStream();
}

do something with oos...

You wouldn't encounter this issue using the ternary operator which is a " shorthand for an if-then-else statement ":

OutputStream oos = _param.get("opath") != null ?
  new FileOutputStream(_param.get("opath").toString()) :
  csocket.getOutputStream();

In this case oos is declared and initialized at once.

Additionally this allows to define the variable oos even final which isn't possbile using the regular if-else-statement.

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