3

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?

  • 3
    No, you can't. Java doesn't support operator overloading etc. – Benjamin Maurer Jun 26 '20 at 12:50
  • 2
    Note that operator overloading is not the only way to achieve that. Scala for example has syntax constructs that allow you to simply define methods that (when called) *look* like language constructs. (Maybe one can argue that this is just an extreme form of operator overloading, but I wouldn't describe it like this). – Joachim Sauer Jun 26 '20 at 12:54
  • 1
    If you are on Java 9 or higher, you could use the factory method `Map.of` from the Map interface to simplify the creation and initialization of immutable maps. Example : `Map map = Map.of("key1","value1", "key2", "value2");` – Eritrean Jun 26 '20 at 13:00

3 Answers3

2

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.

Thomas
  • 174,939
  • 50
  • 355
  • 478
0

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.

andreoss
  • 1,570
  • 1
  • 10
  • 25
0

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.

Ryan1729
  • 940
  • 7
  • 25