Nat Pryce introduced me to a bit of Java syntax that is simple, useful and suprisingly little used or known.
It was a suprise to find this syntax after so long - I've been writing Java on-and-off for 10 years - it isn't new syntax and I've pair-programmed with people who have written more Java than me who didn't use this syntax - I don't know why it isn't used much more frequently.
The syntax
看看下面这段我们可能经常写的代码:
ArrayList list = new ArrayList();
list.add("hello");
list.add("world");
像上面的代码可以改写为:
ArrayList list = new ArrayList(){{
add("hello");
add("world");
}};
呵呵,是不是简化很多啊,有意思。
Any talk of neat syntax must mention Smalltalk
但是此种方法仅限于构造函数中,例如下面的代码是不合法的:
ArrayList list = new ArrayList();
list{{
add("hello");
add("world");
}};
Keep it simple
In lots of cases, I avoid using language features or syntax that is unusual. However, in this case, I think this syntax is easy to understand and deserves to be more commonly used.
And finally
Sponsor me for the National Autistic Society's London to Paris Bike Ride. OK - so it's not relevant to the article, but they've been very good to me and my autistic son, and my fundraising could do with a boost.