Is there a Java equivalent of Javascript with an expression?


Is there a similar way to declare a c-expression in Java (as in Javascript) or are there structural reasons why this is not possible?


For example, this Javascript:
with(obj) { getHomeworkAverage(); getTestAverage(); getAttendance(); } 

... nice and easy. However, it would seem that method calls should be bound to their object (s) every time in Java, without such graceful shortcuts available:

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

This is very redundant and especially annoying when there are many ways to call.


  • So, is there a similar way to declare a statement operator in Java?
  • And if it is possible not , what are the reasons why it is possible in Javascript compared to the impossible in Java?
+4
source share
5 answers

If the obj class is under your control, you can provide a Fluent interface , basically returning this in every function. This will allow you to call method calls like this -

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

+3
source

No, there is no instruction or similar construct in Java.

+8
source

There is no direct equivalent to "c".

If the methods are instance methods, you can specify a link to the target object with a short identifier for use in the 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)); } } 
+7
source

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

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

where each method returns an object.

For more information on first class features: wikipedia

+2
source

So, is there a similar way to declare a statement operator in Java?

No no. The closest will be the import static mechanism described in response to Patricia Shanahan.

And if this is not possible, what are the reasons why this is possible in Javascript compared to the impossible in Java?

These are two completely different languages ​​with different features / strengths / weaknesses. Analogy: a hammer and a screwdriver are both tools, but they are used in different ways.

0
source

All Articles