bigoldrock
bigoldrock

Reputation: 57

Java define variable type on the fly

Give the following snippet of code:

  public boolean singleLine = true;
  if (singleLine) {
    String logLines;
  } else {
    List<String> logLines;
  }

How do you do the above and keep logLines in scope outside of the if/else statement?

Upvotes: 1

Views: 408

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You cannot both (1) keep it in scope and (2) keep it statically typed. You have to pick one or the other.

To keep your variable in scope you could declare it of Object type. This way you would be able to assign any type you wish to it. Unfortunately, this would lose the static typing, meaning that you would have to cast in order to do anything meaningful.

To keep variables statically typed, keep them in separate scopes.

It is likely that neither of these two options would work in your situation. A common approach to solving this is to build a common interface that "unifies" the behavior of several types of objects from the point of view of subsequent code. You could assign different implementations to this interface in different branches, and get the unified behavior after that.

Here is a small illustration of what I mean:

private void processSingle(String str) {
    ... // String-specific code
}
private void processList(List<String> strList) {
    ... // List-specific code
}
// Common interface
interface Wrapper {
    void process();
}
// Using the common interface later on
...
Wrapper w;
if (singleLine) {
    final String singleLineVal = ...
    w = new Wrapper {
        public void process() {
            processSingle(singleLineVal);
        }
    };
} else {
    final List<String> lst = ...
    w = new Wrapper {
        public void process() {
            processList(lst);
        }
    };
}
// Now we can use the unified code:
w.process();

Upvotes: 7

Kon
Kon

Reputation: 10810

Don't define empty variable references inside if statements. That is, don't use conditional flow to create null references. Either define the reference outside the condition then use the clause to instantiate it, or just remove the clause altogether.

Upvotes: 2

Related Questions