[isabelle-dev] ADTs in Scala

Lars Hupel hupel at in.tum.de
Sat Apr 14 13:33:36 CEST 2012

>   object Graph
>   {
>     // public operations to create ADT instances
>   }
>   final class Graph[Key, A] private(rep: SortedMap[Key, (A,
> (SortedSet[Key], SortedSet[Key]))])
>   {
>     // implementation with access to rep
>   }
> The main thing is the "private" in this odd position, which is Odersky's
> way to make the constructor private, but the keep the type itself
> public. This detail seems to have been forgotten in Java -- in fact in a
> recent talk some Java guru admitted that -- which was also my starting
> point to google for "private constructor" to find the above solution.

In fact, the pattern you used is quite common amongst Java developers,
they just call it "Factory Pattern".

> Next inappropriate question for Scala: How to avoid the ubiquitious NPE
> problem of the JVM?

This question is not inappropriate at all. There is no single strategy
to avoid NPEs, but usually, Scala programs make extensive use of
`Option` to wrap anything that comes from a Java library to make sure
that there are no `null`s involved. Scala's API has a nice `Option`
"factory" for that: write `Option(value)`, and get `None` for `null` and
`Some(x)` for `x != null`. Obviously, computations then have to be
rewritten in applicative or monadic style. For the latter, Scala has
sugar in form of "for comprehensions".

On a related note, there is also Scala library support to avoid the
general exception problem on the JVM. (see

-- Lars

More information about the isabelle-dev mailing list