ScalaCheck custom generator examples

Table of Contents1 - Custom generators2 - Built-in ScalaCheck generators3 - How to use ScalaCheck generators4 - More ScalaCheck generators

Writing custom generators for ScalaCheck can be one of the more difficult and/or time-consuming parts of using it. As a result I thought I’d start putting together a list of generators that I have written or seen elsewhere. Unfortunately I can’t credit all the ones I’ve seen in other places because I google’d and copied them many moons ago, but I’ll give credit/attribution to all the ones I can.

Back to top

Custom generators

This is a combination of generators I wrote, and some that I copied from other places and may have modified a little:

How to mix Scala and XML to dynamically generate XML

Problem: You want to dynamically generate XML from your Scala source code, such as creating output for a SOAP web service.


A great feature of Scala’s XML support is that you can interweave XML and regular Scala source code together. This lets you dynamically generate XML from your Scala code.

To create XML with dynamic, embedded data, just put your Scala code in curly braces inside the XML tags, as shown in the following example:

A Java CRUD generator example

I'm still spending a couple of hours a day working on my Java CRUD generator. Technically, because this is all driven by templates, this is also a PHP CRUD generator, and a Python CRUD generator, and in general a programming-language independent CRUD generator, but at the moment it seems easiest to refer to it as a "Java CRUD generator", so I'll call it that for the moment.

How my CRUD generator works

In today's update I'd like to show you how this works. In short, you start with a database table like this one:

Eclipse can generate Java hashCode and equals methods

A nice feature of Eclipse is that you can easily generate hashCode and equals methods for your Java class using the editor. You'll really appreciate this capability when you need to create these methods whenever you're doing anything related to sorting, comparisons, comparators, etc.

Generate Java code from your database design

I don't write much in the way of business application code any more, but if I did, I would generate Java code like crazy.

Think about it, whenever you write database-driven applications, one common denominator is that every database driven project has the database design completed before you start coding. And then, once you start coding, I'll bet 80% of the code is related to what I call CRUD ("create, read, update, delete") functionality.

And you know what -- you can generate this Java database code, either statically, or more powerfully, dynamically.