0

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?

3
  • 1
    What is wrong with def saySomething(t: SomeTrait) = t.kakaw and then s.saySomething(SampleA)? That is, why bother with the type parameter at all? Commented Feb 18, 2011 at 0:28
  • Your specific example isn't possible, because SampleA is not a type, so you cannot pass it as a type parameter. Commented Feb 18, 2011 at 2:36
  • Has your question been answered? Commented Feb 21, 2011 at 15:43

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.