April 19th, 2012

ДР Цертуса 2011

SIP: Dependent type syntax for Scala

The key feature of dependent type systems is that we can write type-valued functions. Recently I encountered a case I could use such one in Scala for improving code readibility. I want to be able to write Reads(res1, res2) to get (ReadsAbstract {val reads = Set(res1, res2)}. Well, there are no type-valued methods in Scala, but I'm still able to get really close to it:

def ReadsGenerator(res: Resource*) = {

  new {type X = ReadsAbstract {val reads = Set(res:_*)}}


Now we can write Reads(res1, res2).X for the purpose I originaly wanted to use Reads(res1, res2) for.

It's worth to define some syntactic sugar for it! First, down with that nasty X. Second, let's add some sugar for generators:

type Reads(res: Resource*) = ReadsAbstract {val reads = Set(res:_*)}


– Such syntax can be easily extended for support of macro types in exactly parallel fashion to current syntax for macro methods. Like type DbTable(jdbcPath: String, creds: DbCredentials) = macro impl

– With this syntax we also obtain nice syntax for dependent tuples and dependent function types.

I would like to thank Nada Amin (ندى أمين) from EPFL for a very insightful discussion on DOT, the future of the Scala type system.