Type safe Scala β Phantom types
Boo! π»
Phantom types parameters is one of my favourite features in type systems with parametric polymorphism : Java, Kotlin, Scala, C#, F#, Haskell, OCaml, and many others.
What is a phantom type parameter? A phantom type parameter is a type parameter that is checked statically by the compiler but not used at runtime. Letβs see an example:
KeyType
is a type parameter that it looks like is useless because we donβt need an instance of it to create a value of type Key
.
What are they good for? They let you tag or mark types with additional information, which ultimately let you define compiler-checked invariants on what order some operations should follow, how they compose, or how they propagate the additional information.
Hereβs an example on how to use phantom type parameters to check statically that we use a private key when decrypting a piece of information encrypted with a public key:
We can further improve that example to contemplate the case where we encrypt with the private key and decrypt with the public key. I leave you the entire snippet of code as a gist because is a bit longer, notice however how an implicit parameter CanDecrypt
is used to establish the encryption/decryption relation we need between the different keys.