通过给定的泛型类型Scala获取类的伴随对象 [英] Get companion object of class by given generic type Scala
本文介绍了通过给定的泛型类型Scala获取类的伴随对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做的是创建一个函数,它将采用一个通用类并在其中使用一个静态方法(对于Java语言,我的意思是它的伴体对象的方法)。
What I am trying to do is to make a function that would take a generic class and use a static method in it (sorry for Java language, I mean method of its companion object).
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
}
任何想法?
推荐答案
Miles Sabin的一个提示可能会给你一个提示:
A gist by Miles Sabin may give you a hint:
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
}
使用 -Ydependent-method-types
标志编译如果使用Scala 2.9.x。
This should be compiled with the -Ydependent-method-types
flag if using Scala 2.9.x.
这篇关于通过给定的泛型类型Scala获取类的伴随对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文