class A
class B extends A
object B {
def createSidekick = new B
}
class C extends A
object C {
def createSidekick = new C
}
object foo {
def bar[T <: C] = {
// T.createSidekick
}
}
在foo.bar中,我想调用给定对象的方法。但是,Scala不允许扩展对象,因此没有明显的方法来实现这一点。完成这种行为的最佳方法是什么?
答案 0 :(得分:1)
这样的东西?
class A
class B extends A
trait Sidekicker[T <: A] {
def createSidekick: T
}
object B extends Sidekicker[B] {
def createSidekick = new B
}
class C extends A
object C extends Sidekicker[C] {
def createSidekick = new C
}
object foo {
def bar(s: Sidekicker[_]) = s.createSidekick
val b = bar(B)
val c = bar(C)
}