In Java maps when we need to insert some values then we use:
map.put(key, value);
In other languages such as with C++ maps or Python dictionaries we can use square brackets:
map['key'] = value
This syntax is not valid with Java maps. Can we change this syntax programmatically by writing some code or using some library?
In Java, you cannot. There are very few languages that allow customization of syntax. Perl, for example, has "pragmas" that are basically other Perl code that preprocesses your script before it runs. It's very powerful but also horrible.
If you need compatibility with Java but like nice syntax, I would suggest Kotlin instead, which (like C++ and Python) allows operator overloading.
Java's grammar cannot be altered at runtime nor at compile time, even operator overloading is not supported (with the exception of + operator overloaded for String. See: How does the String class override the + operator?).
You can overload symbolic operators (such as -,+, /) in other JVM languages such as Scala Groovy and Kotlin, but that's a predefined syntactic sugar, and the syntax itself is still unchanged.
One of the few languages which does allow to change syntax at runtime is Raku, slangs can be added to its grammar at runtime. An example of practical application of this feature is Slang::SQL which makes SQL part of the main syntax.
It would be possible to write a program that looked at your source code before the compiler sees it, and transforms map['key'] = value to map.put(key, value);. But that would likely be more work than makes sense to spend on this. And that doesn't even get into integrating into a build system.
More seriously, if you knew all the keys ahead of time, which I think you might since you used a string literal, you could get fairly similar syntax by using arrays:
Object[] map = new Object[10];
map[KEY] = value;
where key is an integer constant like
public static final int KEY = 0;
Hashmaps/Dictionaries do something similar under the hood.
Edit: I have rewritten the question to hopefully make it more understandable.
I do not want to overload!
If you have the following code:
ImmutableObject mutableReference = new ImuttableObject();
mutableReference = mutableReference.doStuff(args);
Can a compile time or pre-compile time process replace defined text formats? For example:
DEFINE X.=Y AS X = X.Y
could replace
mutableReference .= doStuff(args) with mutableReference = mutableReference.doStuff(args);
So some process knows that the code before ".=" is X and after is Y. Similar to syntactic sugar, before compiling or during, just replace X.=Y with X = X.Y.
Below is the old version of the question.
I have the following "form" of code for lack of a better word.
turnStates = turnStates.add(currentState); // log end of turn state.
//turnStates.=add(currentState);
//turnStates=.add(currentState);
Where turnStates can be a reference to any immutable object.
I would like it to look like the code commented out or similar.
Much like integers that have ++ and += I'd like a way to write my own for my immutables.
I think I recall some pre-processor stuff from C++ that I think could replace predefined text for code snippets. I was wondering if there was a way in java to define a process for replacing my desired code for the working code at compile time.
I'm sure you could make the IDE do it, but then you can't share the code with others not running a pre-configured IDE.
Edit:
turnStates is immutable and returns a different object on a call to add. It is test code and I have my reasons why a list, or as it is at the moment acting more like a stack, is immutable. Irrelevant for the question as I could simply replace it with
player = player.doSomething(args) where doSomething(args) returns a Player instance. Player is just a small part of the model and is costless to be immutable.
I know Overloads and syntax can't be changed in Java. As I tried to portray originally, sorry if it didn't come across this way is:
I was hoping that I wasn't aware of a syntax to do with maybe the # sign that could replace text before compiling. So for example:
DEFINE X.=Y AS X = X.Y where X = turnStates and Y = add() in my example.
But as the answer I upvoted said. I'll check out Scala as the answer seems to be no.
No. Java explicitly does not support operator overloading for user defined data types. However, scala is a JVM hosted language and does.
Unlike C++,Java doesn't support operator overloading.But Scala or Groovy does.
Scala can be integrated into Java but the operator overloading integration part is still not directly supported by Java as you will not be able to use the operator itself but something like #eq(...) for the "=" operator.
Check this link out for a little more detail if you want to know about Scala integration into java
Bottom line:
operator overloading is not supported by Java
And if your project requires a lot of vector addition, substraction,etc. i.e. lot of custom operators then a good suggestion would be using C# as your choice of language which is a Java like language
In programs such as Unity3D that have Vector2/Vector3's etc (I use C# coding in the program), you can multiply Unity's Vector objects by a float simply using the '*' operand and no explicit methods. Eg:
Vector2 oldVector = new Vector2(10f, 10f);
Vector2 newVector = oldVector * -2f
And then newVector would have the value (-20f, -20f).
As opposed to something using methods like:
Vector2 oldVector = new Vector2(10f, 10f);
Vector2 newVector = oldVector.multiply(-2f);
Basically how would you tell Java to handle this/implement it into your class? Is there even a way?
I realise this may just be convoluted and that it's likely significantly easier to just use methods, but I feel like it would be interesting to learn and maybe useful at a later stage.
Very simple: Java doesn't allow for operator overloading; which is the concept behind "hiding" a method call that way.
You see, in essence, that code is dealing with object/reference types in the end. So even when other languages allow you to write "*" instead of "multiply"; in the end, there is still a method that gets invoked.
Basically that was a decision made on purpose when Java was put in place. Many people disliked operator overloading (pointing at C++ where such things were often misused); so the argument was made that Java should not allow for it.
If your main concern is to use * instead of multiply; there are plenty of other languages that run on the JVM (Scala for example) that give you operator overloading (but to be honest: Scala doesn't have operator overloading, but it allows you to name your method "*").
Simply put: You can't.
Java does not support operand overloading. There are other languages that build on the JVM (groovy, kotlin and scala) that support it - but ultimately they're doing the same as your second example.
In detail: The Java Spec sheet does not account for any operator overloading (for example, here: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17)
I've got a bit of an interesting challenge
To the point:
I want to allow a user to enter an expression in a text field, and have that string treated as a python expression. There are a number of local variables I would like to make available to this expression.
I do have a solution though it will be cumbersome to implement. I was thinking of keeping a Python class source file, with a function that has a single %s in it. When the user enters his expression, we simply do a string format, and then call Jython's interpreter, to spit out something we can execute. There would have to be a number of variable declaration statements in front of that expression to make sure the variables we want to expose to the user for his expression.
So the user would be presented with a text field, he would enter
x1 + (3.5*x2) ** x3
and we would do our interpreting process to come up with an open delegate object. We then punch the values into this object from a map, and call execute, to get the result of the expression.
Any objections to using Jython, or should I be doing something other than modifying source code? I would like to think that some kind of mutable object akin to C#'s Expression object, where we could do something like
PythonExpression expr = new PythonExpression(userSuppliedText)
expr.setDefaultNamespace();
expr.loadLibraries("numPy", /*other libraries?*/);
//comes from somewhere else in the flow, but effectively we get
Map<String, Double> symbolValuesByName = new HashMap<>(){{
put("x1", 3.0);
put("x2", 20.0);
put("x3", 2.0);
}};
expr.loadSymbols(symbolValuesByName);
Runnable exprDelegate = expr.compile();
//sometime later
exprDelegate.run();
but, I'm hoping for a lot, and it looks like Jython is as good as it gets. Still, modifying source files and then passing them to an interpreter seems really heavy-handed.
Does that sound like a good approach? Do you guys have any other libraries you'd suggest?
Update: NumPy does not work with Jython
I should've discovered this one on my own.
So now my question shifts: Is there any way that from a single JVM process instance (meaning, without ever having to fork) I can compile and run some Python code?
If you simply want to parse the expressions, you ought to be able to put something together with a Java parser generator.
If you want to parse, error check and evaluate the expressions, then you will need a substantial subset of the functionality a full Python interpreter.
I'm not aware of a subset implementation.
If such a subset implementation exists, it is unclear that it would be any easier to embed / call than to use a full Python interpreter ... like Jython.
If the powers that be dictate that "thou shalt use python", then they need to pay for the extra work it is going to cause you ... and the next guy who is going to need to maintain a hybrid system across changes in requirements, and updates to the Java and Python / Jython ecosystems. Factor it into the project estimates.
The other approach would be to parse the full python expression grammar, but limit what your evalutor can handle ... based on what it actually required, and what is implementable in your project's time-frame. Limit the types supported and the operations on the types. Limit the built-in functions supported. Etcetera.
Assuming that you go down the Java calling Jython route, there is a lot of material on how to implement it here: http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
All modern languages require this because referencing a function and calling a function are separate actions.
For example,
def func():
print "hello"
return 10
a = func
a()
Clearly, a = func and a = func() have very different meanings.
Ruby--the most likely language you're thinking of in contrast--doesn't require the parentheses; it can do this because it doesn't support taking references to functions.
In languages like Python and JavaScript, functions are first–class objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the () in myfunc()) actually constitute an operator, just like + or *. Instead of meaning "add this number to another number" (in the case of +), () means "execute the preceding function". This is necessary because it is possible to use a function without executing it. For example, you may wish to compare it to another function using ==, or you may wish to pass it into another function, such as in this JavaScript example:
function alertSomething(message) {
alert(message);
}
function myOtherFunction(someFunction, someArg) {
someFunction(someArg);
}
// here we are using the alertSomething function without calling it directly
myOtherFunction(alertSomething, "Hello, araneae!");
In short: it is important to be able to refer to a function without calling it — this is why the distinction is necessary.
At least in JS, its because you can pass functions around.
var func = new Function();
you can then so something like
var f = func
f()
so 'f' and 'func' are references to the function, and f() or func() is the invocation of the function.
which is not the same as
var val = f();
which assigns the result of the invocation to a var.
For Java, you cannot pass functions around, at least like you can in JS, so there is no reason the language needs to require a () to invoke a method. But it is what it is.
I can't speak at all for python.
But the main point is different languages might have reasons why syntax may be necessary, and sometimes syntax is just syntax.
I think you answered it yourself:
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
Consider the following:
if (colorOfTheSky == 'blue')
vs:
if (colorOfTheSky() == 'blue')
We can tell just by looking that the first checks for a variable called colorOfTheSky, and we want to know if its value is blue. In the second, we know that colorOfTheSky() calls a function (method) and we want to know if its return value is blue.
If we didn't have this distinction it would be extremely ambiguous in situations like this.
To answer your last question, I don't know of any languages that don't have this distinction.
Also, you probably have a design problem if you can't tell the difference between your methods and your properties; as another answer points out, methods and properties have different roles to play. Furthermore it is good practice for your method names to be actions, e.g. getPageTitle, getUserId, etc., and for your properties to be nouns, e.g., pageTitle, userId. These should be easily decipherable in your code for both you and anyone who comes along later and reads your code.
If you're having troubles, distinguishing between your properties and methods, you're probably not naming them very well.
In general, your methods should have a verb in them: i.e. write, print, echo, open, close, get, set, and property names should be nouns or adjectives: name, color, filled, loaded.
It's very important to use meaningful method and property names, without it, you'll find that you'll have difficulty reading your own code.
In Java, I can think of two reasons why the () is required:
1) Java had a specific design goal to have a "C/C++ like" syntax, to make it easy for C and C++ programmers to learn the language. Both C and C++ require the parentheses.
2) The Java syntax specifically requires the parentheses to disambiguate a reference to an attribute or local from a call to a method. This is because method names and attribute / local names are declared in different namespaces. So the following is legal Java:
public class SomeClass {
private int name;
private int name() { ... }
...
int norm = name; // this one
}
If the () was not required for a method call, the compiler would not be able to tell if the labeled statement ("this one") was assigning the value of the name attribute or the result of calling the name() method.
The difference isn't always explicit in VBA. This is a call to a Sub (i.e. a method with no return value) which takes no parameters (all examples are from Excel):
Worksheets("Sheet1").UsedRange.Columns.AutoFit
whereas this is accessing an attribute then passing it as a parameter:
MsgBox Application.Creator
As in the previous example, parentheses are also optional around parameters if there is no need to deal with the return value:
Application.Goto Worksheets("Sheet2").Range("A1")
but are needed if the return value is used:
iRows = Len("hello world")
Because referencing and calling a method are two different things. Consider X.method being the method of class X and x being an instance of X, so x.method == 'blue' would'nt ever be able to be true because methods are not strings.
You can try this: print a method of an object:
>>> class X(object):
... def a(self):
... print 'a'
...
>>> x=X()
>>> print x.a
<bound method X.a of <__main__.X object at 0x0235A910>>
Typically properties are accessors, and methods perform some sort of action. Going on this assumption, it's cheap to use a property, expensive to use a method.
Foo.Bar, for example, would indicate to me that it would return a value, like a string, without lots of overhead.
Foo.Bar() (or more likely, Foo.GetBar()), on the other hand, implies needing to retrieve the value for "Bar", perhaps from a database.
Properties and methods have different purposes and different implications, so they should be differentiated in code as well.
By the way, in all languages I know of the difference in syntax is explicit, but behind the scenes properties are often treated as simply special method calls.