Question


Is there a similar way to declare a with-statement in Java (as in Javascript), or are there structural reasons why this would not be possible?


For example, this Javascript:

with(obj)
{
  getHomeworkAverage();
  getTestAverage();
  getAttendance();
}

...is nice and easy. However, it would seem that method calls have to be chained to their object(s) every time in Java, with no such graceful shortcuts avaiable:

obj.getHomeworkAverage();
obj.getTestAverage();
obj.getAttendance();

This is very redundant, and especially irritating when there are many methods to call.


  • So, is there any similar way to declare a with-statement in Java?
  • And if this is not possible, what are the reasons that it is possible in Javascript as compared to not possible in Java?
Was it helpful?

Solution 3

If the class of obj is under your control, you could provide a Fluent interface, basically returning this in every function. This would let you chain method calls like this-

obj.getHomeworkAverage().getTestAverage().getAttendance();

OTHER TIPS

There is no direct equivalent of "with".

If the methods are instance methods, you can give the target object reference a short identifier for use in a block:

{
  Student s = student;
  s.getHomeworkAverage();
  s.getTestAverage();
  s.getAttendance();
}

If the methods are static, you can use "import static":

import static java.lang.Math.*;

public class Test {
  public static void main(String[] args) {
    System.out.println(sqrt(2));
  }
}

No, there's no with statement or a similar construct in Java.

There is a reason why you can't do this in Java. Perhaps the most obvious is that functions are not first-class objects in Java and therefore you cannot simply have a name referring to the function - it must be under a class. As mentioned by Karthik T, the way you would shorten this could be just creative use of whitespace:

obj
    .meth1()
    .meth2()
    .meth3()

where each method returns the object.

For more info on First-Class Functions: wikipedia

So, is there any similar way to declare a with-statement in Java?

No, there is not. The closest thing would be the import static mechanism described in Patricia Shanahan's answer.

And if this is not possible, what are the reasons that it is possible in Javascript as compared to not possible in Java?

They're two entirely different languages with different features/strengths/weaknesses. An analogy: A hammer and a screwdriver are both tools, but they are used in different ways.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top