Array, list, set, map, tuple, record literals in Java
var map = new Object(); map["a"] = 1; map["b"] = 2; map["c"] = 3;
Instead, you’d probably write
var map = { "a":1, "b":2, "c":3 };
Specifically, when passing complex parameters to an API function, this turns out to be a very handy syntax.
What about these things in Java?
I’ve recently posted about a workaround that you can use for creating a “List literal” using Arrays.asList(…) here:
http://blog.jooq.org/2011/10/28/javas-arrays-aslist-is-underused/
This is somewhat OK. You can also construct arrays when you assign them, using array literals. But you cannot pass an array literal to a method:
// This will work: int[] array = { 1, 2, 3 }; // This won't: class Test { public void callee(int[] array) {} public void caller() { // Compilation error here: callee({1, 2, 3}); } }
Brian Goetz’s mentioning of various literals on lambda-dev
Missing this feature for quite a while, I was very thrilled to read Brian Goetz’s mentioning of them on the lambda-dev mailing list:
http://mail.openjdk.java.net/pipermail/lambda-dev/2012-May/004979.html
The ideas he was listing were these:
#[ 1, 2, 3 ] // Array, list, set #{ "foo" : "bar", "blah" : "wooga" } // Map literals #/(\d+)$/ // Regex #(a, b) // Tuple #(a: 3, b: 4) // Record #"There are {foo.size()} foos" // String literal
Unfortunately, he also added the following disclaimer:
Not that we’d embrace all of these immediately (or ever)
Obviously, at this stage of current Java language evolvements for Java 8, he cannot make any guarantee whatsoever about what might be added in the future. But from a jOOQ perspective, the idea of being able to declare tuple and record literals (with the appropriate backing language-support for such types!) is quite thrilling. Imagine selecting arbitrary tuples / records with their associated index/type, column/type pairs. Imagine a construct like this one in Java or Scala (using jOOQ):
// For simplicity, I'm using Scala's val operator here, // indicating type inference. It's hard to guess what true // record support in the java language should look like for (val record : create.select( BOOK.AUTHOR_ID.as("author"), count().as("books")) .from(BOOK) .groupBy(BOOK.AUTHOR_ID) .fetch()) { // With true record support, you could now formally extract // values from the result set being iterated on. In other // words, the formal column alias and type is available to // the compiler: int author = record.author; int books = record.books; }
Obviously, this is only speculation, but you can see that with true tuple / record support in the Java language, a lot of features would be unleashed in the Java universe with a very high impact on all existing libraries and APIs
Stay tuned!
Reference: Array, list, set, map, tuple, record literals in Java from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog.