你能在Scala中的类参数化中动态调用一个对象方法吗?

时间:2011-02-18 00:02:12

标签: scala scala-2.8

我对Scala很新,但我正在尝试实现以下情况。假设我有一个特点:

trait SomeTrait {
  def kakaw
}

两个扩展它的Scala对象:

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]

这在Scala中是否可行?

2 个答案:

答案 0 :(得分: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 = SampleA@42c71191

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

scala> implicit val sampleB = new SampleB
sampleB: SampleB = SampleB@53601a4f

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

scala> val s = new SomeOther
s: SomeOther = SomeOther@5947e54e

scala> s.saySomething[SampleA]
res0: String = Woof

答案 1 :(得分:3)

这有点令人困惑,因为你需要有一个你的类型的实例来行动。只是传递一个类型可能会让编译器开心,但你肯定想确保提供你想要使用的某种类型的实例。

(考虑到单例对象,可能会有一个使用隐式证据参数的工作,但除非真的需要,否则我不会这样做。)

那么,在你的情况下你为什么不说

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

val s = new SomeOther
s.saySomething(SampleA)