我想要做的是制作一个通用类并使用静态方法的函数(对于Java语言,我的意思是它的伴随对象的方法)。
trait Worker {def doSth: Unit} class Base object Base extends Worker // this actually wouldn't work,just to show what I'm trying to achieve def callSthStatic[T that companion object is <: Worker](implicit m: Manifest[T]) { // here I want to call T.doSth (on T object) m.getMagicallyCompanionObject.doSth }
有任何想法吗?
解决方法
A gist by Miles Sabin可能会给你一个提示:
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 }
如果使用Scala 2.9.x,则应使用-Ydependent-method-types标志编译。