2011-02-18 112 views
1

我对Scala很新,但我试图实现以下情况。假设我有一个特点:你能在Scala中动态调用一个对象方法吗?

trait SomeTrait { 
    def kakaw 
} 

和两个斯卡拉对象扩展它:

object SampleA extends SomeTrait { 
    def kakaw = "Woof" 
} 

object SampleB extends SomeTrait { 
    def kakaw = "Meow" 
} 

我想要做的就是调用基于参数的函数调用这两个对象的功能之一。例如(我知道这是正确的,从最远的东西):

class SomeOther { 
    def saySomething[T] = T.kakaw 
} 

所以我可以这样做:

val s = new SomeOther 
s.saySomething[SampleA] 

在斯卡拉这是在所有可能的?

+1

什么是错的`高清saySomething(T:SomeTrait)= t.kakaw`然后`s.saySomething(SampleA)`?也就是说,为什么要打扰类型参数呢? – 2011-02-18 00:28:51

回答

3

这有点令人困惑,因为您需要让您的类型的实例进行操作。只是传递一个类型可能会使编译器感到高兴,但是您一定要确保提供您想要使用的某种类型的实例。

(考虑单一对象有可能是围绕使用隐式证据参数的工作,但我不会做,除非真正需要的。)

所以,你的情况你为什么不只是说

class SomeOther { 
    def saySomething(obj: SomeTrait) = obj.kakaw 
} 

val s = new SomeOther 
s.saySomething(SampleA) 
4
& scala 
Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_23). 
Type in expressions to have them evaluated. 
Type :help for more information. 

scala> trait SomeTrait { 
    | def kakaw : String 
    | } 
defined trait SomeTrait 

scala> class SampleA extends SomeTrait { 
    | def kakaw = "Woof" 
    | } 
defined class SampleA 

scala> implicit val sampleA = new SampleA 
sampleA: SampleA = [email protected] 

scala> class SampleB extends SomeTrait { 
    | def kakaw = "Meow" 
    | } 
defined class SampleB 

scala> implicit val sampleB = new SampleB 
sampleB: SampleB = [email protected] 

scala> class SomeOther { 
    | def saySomething[ T <: SomeTrait](implicit target : T) = target.kakaw 
    | } 
defined class SomeOther 

scala> val s = new SomeOther 
s: SomeOther = [email protected] 

scala> s.saySomething[SampleA] 
res0: String = Woof 
相关问题