Fork me on GitHub

Hacking Scala

#scala #hacking

January 19, 2014 at 7:54pm

Advanced Type Constraints with Type Classes

This weekend I was continuing my work on the next version of Scaldi. Once again I faced the problem that was bothering me quite some time. In Scaldi you can inject a dependency with something like this:

val server = inject [HttpServer]

In this case inject method will get HttpServer class as a type argument and everything works as expected. But what would happen if you forget to specify the type or you just defined the type of the server but don’t provide it explicitly to the inject method? Will it even compile or maybe type inference will be able to figure out the type?

val server = inject
val server1: HttpServer = inject

Unfortunately, in both cases it will compile, but the inferred type would be Nothing. It appears to be a known problem and it will not be fixed. Ideally I would like to see a compilation error in this case, so I started to look for a solution. After some time I actually was able to find the way to prevent Nothing inference and, by taking this idea even further, found a way to define type constraints in a very generically in the method signature. They will allow you, for example, to describe union types with (T =:= String) Or (T =:= Int) or even more complex rules like (T <:< Color) And Not[T =:= Color] And Not[(T =:= Yellow.type) Or (T =:= Blue.type)].

Keep reading