Can you call an object method dynamically off class parameterization in Scala?
I'm quite new to Scala, 开发者_运维问答but I'm trying to implement the following situation. Suppose I have a trait:
trait SomeTrait {
def kakaw
}
And two Scala objects that extend it:
object SampleA extends SomeTrait {
def kakaw = "Woof"
}
object SampleB extends SomeTrait {
def kakaw = "Meow"
}
What I'd like to do is call one of these two object functions based on a parameterized function call. For example (and I know this is the furthest thing from correct):
class SomeOther {
def saySomething[T] = T.kakaw
}
So I can do something like:
val s = new SomeOther
s.saySomething[SampleA]
Is this at all possible in Scala?
& 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
It’s a bit confusing because you’ll need to have an instance of your type to act on. Just passing a type may make the compiler happy but you certainly want to make sure that you supply the very instance of some type you want to work with.
(Considering singleton objects there may be a work around using implicit evidence parameters for that, but I wouldn’t do that unless really needed.)
So, in your case why don’t you just say
class SomeOther {
def saySomething(obj: SomeTrait) = obj.kakaw
}
val s = new SomeOther
s.saySomething(SampleA)
精彩评论