Create a gist now

Instantly share code, notes, and snippets.

Access to companion object of Foo via implicit resolution
trait Companion[T] {
type C
def apply() : C
}
object Companion {
implicit def companion[T](implicit comp : Companion[T]) = comp()
}
object TestCompanion {
trait Foo
object Foo {
def bar = "wibble"
// Per-companion boilerplate for access via implicit resolution
implicit def companion = new Companion[Foo] {
type C = Foo.type
def apply() = Foo
}
}
import Companion._
val fc = companion[Foo] // Type is Foo.type
val s = fc.bar // bar is accessible
}
@nhap96
nhap96 commented May 14, 2016 edited

Hi, could you explain why in line 7 the companion method is defined as implicit def but not def, and is there any case the implicit modifier here would be useful? Thank you.

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