Skip to content

Instantly share code, notes, and snippets.

@milessabin
Created February 4, 2012 15:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save milessabin/5a76bb0c7a51bea3fabe to your computer and use it in GitHub Desktop.
Save milessabin/5a76bb0c7a51bea3fabe to your computer and use it in GitHub Desktop.
Another pass at unboxed newtype in Scala
type Tagged[T] = { type Tag = T }
type @@[T, U] = T with Tagged[U]
class MyStringOps(s : String) {
def mySize = s.size
}
// Use of Any means we forget the underlying type
type MyString = Any @@ MyStringOps
def MyString(s : String) = s.asInstanceOf[MyString]
// Implicit resolution is driven by the tag
implicit def myStringOps(ms : MyString) = new MyStringOps(ms.asInstanceOf[String])
val s = "foo"
val ms = MyString(s)
ms eq s // true, showing that we have an unboxed representation
val s2 : String = ms // Does not compile
ms.size // Does not compile
ms.mySize // Compiles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment