[prev in list] [next in list] [prev in thread] [next in thread] 

List:       openjdk-discuss
Subject:    2 new feature proposals: class extensions and import aliases
From:       Behrang Saeedzadeh <behrangsa () gmail ! com>
Date:       2014-09-21 5:45:53
Message-ID: CAERAJ+8YOT7=cC7s13zQYMT1A=AYJag6z2+QqHBGbC+W-CdFNw () mail ! gmail ! com
[Download RAW message or body]

Hi all,

This is nothing new as there are other languages that have this feature
already, but now that Java has syntactical support for closures, etc. I
think it would be nice if it was possible to augment classes with custom
methods.

For example, if I wanted to add a method times(Runnable c) to Integer that
runs the given block multiple times so that I could type the following code:

5.times(() -> {
System.out.println("Hello, World");
})


All I needed to do was to define an "extension" for Integer:

*com.foo.IntegerExtension*
*========================*

extension IntegerExtension extends Integer {
 public void times(Runnable r) {
for (int i = this; i < count; i++) {
c.run();
}
}

}

Then I can activate the IntegerExtension explicitly by importing it into a
class:

*com.foo.Main*
*============*

import com.foo.IntegerExtension;

public class Main {
 public static void main(String[] args) {
5.times(() -> {
System.out.println("Hello, World");
})
}
}


Of course this is just to show the idea and the implementation can be quite
different.

Another *very simple* feature that I wish Java had is importing a class
with an alias, similar to Groovy:

import java.util.Date;
import java.sql.Date as SDate;

SDate sDate = ...;
Date date = ...;

// or

import java.awt.Point as Vector;

spaceship.move(new Vector(+5, -10));


What do you fellows think?

Best regards,
Behrang
http://www.behrang.org
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic