Skip to content

Instantly share code, notes, and snippets.

@milessabin
Created February 13, 2012 18:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milessabin/1819087 to your computer and use it in GitHub Desktop.
Save milessabin/1819087 to your computer and use it in GitHub Desktop.
Access to companion object via implicit resolution
// See this mailing list thread for context:
// https://groups.google.com/d/topic/scala-language/ImqJuGylyi8/discussion
case class Companion[-C, T](t : T)
trait Publish[C, T] { self : T =>
implicit val companion = Companion[C, T](this)
}
trait StaticKey {
def key : String
}
object A extends StaticKey with Publish[A, StaticKey] {
val key = "KeyA"
}
object B extends StaticKey with Publish[B, StaticKey] {
val key = "KeyB"
}
trait Item {
// Resolve reference to companion implicitly ... note use of this.type
def key(implicit c : Companion[this.type, StaticKey]) = c.t.key
}
class A extends Item
class B extends Item
object TestKey extends App {
val a = new A
assert(a.key eq A.key)
val b = new B
assert(b.key eq B.key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment