Is it possible to create a custom statement in Java?

Similarly Is it possible to create a new operator in C #? Can I create my own operator for Java? At first I would say no, since you cannot overload, but again, String supports + and + = (implicitly through StringBuilder at runtime, etc.).

+6
source share
5 answers

Java does not allow this.

However, if you want to achieve this syntax, being able to run your code on the JVM (and with other Java code), you can look at Groovy, which has operator overloading (and with which you can also use DSL for short syntax, which will have similar effects using custom operators).

Note that defining user statements (and not just overloading) is a big deal in any language, as you will need to somehow change the lexer and grammar.

+7
source

No, Java does not expand this way. You cannot add operators, and you cannot even overload built-in operators such as + . Even standard library classes, such as BigInteger, must use methods such as add() , rather than operators like + .

Scala (another static JVM language) will go around this using method calls rather than built-in operators, and resolving any characters in method names, so you can define new methods that seem to be operators, i.e.

 a + 1 

- syntactic sugar for:

 a.+(1) 
+11
source

No, you cannot overload special characters for operators in Java.

0
source

Like everyone else, you absolutely cannot add new operators in Java. However, other Java-friendly JVM languages, such as Groovy, will allow you to define new statements from existing statement tokens.

0
source

Not. Read this article for an argument why they should not be: http://java.dzone.com/articles/why-java-doesnt-need-operator

You can use another language, such as Scala, to achieve this on the Java platform. - fooobar.com/questions/1365 / ...

0
source

Source: https://habr.com/ru/post/913982/


All Articles