-
-
Save jcarver989/2fbb1ee926f57373aac5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// let's us tag primitives with made up types | |
type Tagged[T] = { type Tag = T } | |
// have to declare our type annotations for use below | |
trait BizoIdTag | |
trait PartnerIdTag | |
trait AppNexusIdTag | |
// afaik effectively this treats the lhs (ex BizoId) of the alias as a subclass | |
// of the primitive, only with the added type | |
type BizoId = String with Tagged[BizoIdTag] | |
type PartnerId = Long with Tagged[PartnerIdTag] | |
type AppNexusId = Long with Tagged[AppNexusIdTag] | |
// Spark on Scala 2.10 now, which means we can use value classes | |
// afaik at runtime we don't allocate new objects at all | |
implicit class TaggedString(val data: String) extends AnyVal { | |
// looks scary, but this cast actually can't fail | |
def bizoId = data.asInstanceOf[BizoId] | |
} | |
implicit class TaggedLong(val data: Long) extends AnyVal { | |
def partnerId = { | |
require(data >= 1) // oooooo validation! | |
data.asInstanceOf[PartnerId] | |
} | |
def appNexusId = data.asInstanceOf[AppNexusId] | |
} | |
def doSomething(bizoId: BizoId, appNexusId: AppNexusId): String = { | |
"Hello World" | |
} | |
doSomething("129IDKAJDf".bizoId, 12345.appNexusId) // yay! | |
doSomething("129IDKAJDf".bizoId, 12345.partnerId) // compiler Error! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playing around with these techniques gives me some errors.
I have
That gives me this stacktrace.
Edit: I left out one important piece.
I then try and use it like :
Have you ever seen anything like this? In any case, nice write up . Thanks!