JohnEye
JohnEye

Reputation: 6895

Declaring variable to be of certain type

Let's say we have the following block of code:

if (thing instanceof ObjectType) {
    ((ObjectType)thing).operation1();
    ((ObjectType)thing).operation2();
    ((ObjectType)thing).operation3();
}

All the typecasting makes the code look ugly, is there a way of declaring 'thing' as ObjectType inside that block of code? I know I could do

OjectType differentThing = (ObjectType)thing;

and work with 'differentThing' from then on, but that brings some confusion to the code. Is there a nicer way of doing this, possibly something like

if (thing instanceof ObjectType) {
    (ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
    thing.operation1();
    thing.operation2();
    thing.operation3();
}

I am pretty sure this question has been asked in the past, I couldn't find it though. Feel free to point me to the possible duplicate.

Upvotes: 7

Views: 147

Answers (3)

Setomidor
Setomidor

Reputation: 954

Sadly, this is not possible.

The reason is that "thing" in this scope will always be of the same object type, and you cannot recast it within a block of code.

If you dislike having two variable names (like thing and castedThing), you could always create another function;

if (thing instanceof ObjectType) {
    processObjectType((ObjectType)thing);
}
..

private void processObjectType(ObjectType thing) {
    thing.operation1();
    thing.operation2();
    thing.operation3();
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

Once a variable is declared, it's type cannot change. Your differentThing approach is the correct one:

if (thing instanceof ObjectType) {
    OjectType differentThing = (ObjectType)thing;
    differentThing.operation1();
    differentThing.operation2();
    differentThing.operation3();
}

I wouldn't call it confusing, either: as long as the scope of the differentThing variable is limited to the body of the if operator, it is clear to the readers what is going on.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1504162

No, once a variable is declared, the type of that variable is fixed. I believe that changing the type of a variable (potentially temporarily) would bring far more confusion than the:

ObjectType differentThing = (ObjectType)thing;

approach you believe to be confusing. This approach is widely used and idiomatic - where it's required at all, of course. (This is typically a bit of a code smell.)

Another option is to extract a method:

if (thing instanceof ObjectType) {
    performOperations((ObjectType) thing);
}
...

private void performOperations(ObjectType thing) {
    thing.operation1();
    thing.operation2();
    thing.operation3();
}

Upvotes: 9

Related Questions