Monday, February 18, 2013

Project coin and operator overloading

Today there a lot of programming languages running on the JVM. one of the arguments of the advocates of these languages is that java is old language that require you to write a lot of code while you can simplify and shorten your code if you will use language like scala. This is the reason why in java 7 there is a new project - coin project that wish to simplify the syntax of java. in java 7 the following features were added: 1. using string and enums for switch statement 2. enable adding more than one exception in the catch clause. 3. the diamond operator in generics (removing generics in the constructor) 4. ability to call exotic names of methods that exist in other JVM languages - i will refer to it soon. and one still in thinking process: 5. adding notation to access collection - this one i would like to discuss. Collections are widely used in java and array is pretty much old fusion, however, it is very nice that you can write array[i]. It can be very nice if you can do it to collections as well.
for (int i = 0; i < list.size();i++){
   list[i] = something(i);
}

first, i'm not sure it is such a bright idea since it discourage users to use iterator, but there is something appealing in this idea. so if you wish to create a solution for it, you can go in two ways: collections that provide us index should implement an interface, the list interface - so array should implement list too? and the operator [] will be overloaded only on the list interface. this solution is not generic solution and you can ask yourself why this interface should get operator overloading and other java objects not. or finally we will have operator overloading in java and the integration with languages like scala will be much simpler. it can be nice if you will be able to write the following code:

if (newDate > oldDate){
doSomething();
}

this is really can be nice... and it will also resolve number 4 that i said that i will refer to it later. now you don't need exotic names for functions that support operator overloading. however, operator overloading has problem in java since in java we have only two types of variables: primitive & references. and operators refers to variable and not for objects, let examine the following code:
if (person1 == person2){
   doSomething();
}

the == operator refer to the reference and not to the object. so now if you wish to overload the == operator you can't check if the references point on the same object! so it is a problem to implement operator overloading in java. so you can add syntax sugar in the coin project but it is not feet to a common standard. and one more thing what happened if the object itself is null, what happened in the operator invocation. so i guess, full operator oveloading is not simple in java. but i really be happy to see more thoughts about this idea.

No comments: