Created
February 13, 2012 18:59
-
-
Save milessabin/1819087 to your computer and use it in GitHub Desktop.
Access to companion object via implicit resolution
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
// 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