Wednesday, January 30, 2013

Java to Scala idioms: id list from object list

Well, i was amazed.

I just needed to get a list of IDs of database-stored objects, in order to pass them for later-on updates with the 'where ... in' query. And got that with scala mind-blowing way. Instead of Java (please omit comments about lots of auto-boxing and array creation etc -- its only verbosity-related sample):

List dbObjects = ...
ArrayList idArray = new ArrayList(dbObjects.size());
for(DBObject o : dbObjects) {

I would just write something like

val ids =

And that's it!

Moreover, I'm now using slick with lifted embedding. For it, i need to map objects I want to store in DB to tuples consistent with db schema (prior to insert). I'm now about to do this by providing a mapping function in the Table descendants describing DB schema, and using it whenever I want to store objects. Just need to  think of types a bit so it is consistent,but general use would be, instead of:

DBObjects.insertAll( => (,, ...)) 

I would use

DBObjects.insertAll(objects), while inside this thing would use its own mapping functions.
Great stuff about it is that it is all compile-time checked -- e.g, if I change schema, I will get compilation errors about the tuples don't match on that conversion function.

Isn't that nice?

No comments: