2011-02-18 101 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 
相關問題