Skip to content

Instantly share code, notes, and snippets.

@retronym
Forked from milessabin/gist:89c9b47a91017973a35f
Created September 21, 2011 20:25
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save retronym/8fe2c19e4431e817015b to your computer and use it in GitHub Desktop.
Save retronym/8fe2c19e4431e817015b to your computer and use it in GitHub Desktop.
Unboxed newtype in Scala (with sugar)
class User
class Checkin
type Tagged[T] = { type Tag = T }
type @@[T, U] = T with Tagged[U]
def tag[T] = new {
def apply[U](u : U) : U @@ T = u.asInstanceOf[U @@ T]
}
def fetch[A](id: Int @@ A): A = null.asInstanceOf[A]
def main(args: Array[String]): Unit = {
val id = tag[Checkin](10)
fetch[Checkin](id) // Compiles
// fetch[User](id) // Does not compile
val ids = tag[User](1) :: tag[User](2) :: tag[User](3) :: Nil
val users : List[Int @@ User] = ids // Compiles
// val checkins : List[(Int with Tagged[Checkins])] = ids // Does not compile
}
@paulp
Copy link

paulp commented Sep 21, 2011

Maybe it doesn't compile because there is no "Checkins" type. (Ha ha.)

@milessabin
Copy link

@paulp Oops ... corrected in the original (it still doesn't compile ;-).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment