0

This may be a very stupid question, but as I'll try it anyway. I'm trying to use wildcards with a typed class so I can get the properties of it.

I am trying to provide a sintax (DSL-like) to create objects that would treat the incoming message accordingly to it's type parametrization . I'd really like the sintax looks something like this:

// Types of message
trait TypeMessage
case class TypeMessage1 extends TypeMessage{
    val a : String,
    val b : Int
}
case class TypeMessage2 extends TypeMessage{
    val c : Double,
    val d : String
}

// Here is the problem
class TreatMsg[T <: TypeMessage] {
    // I'm using a random sintax here, just for ilustration
    def getParamInfo( variable : ?? ) = { 
        println("name: " + variable.name + "  value: " + variable.val + "  type: " + variable.val.getClass)
    }
}
object TreatMsg{
    def apply[T <: TypeMessage] = new TreatMsg[T]
}


// Creating actors
TreatMsg[TypeMessage1].getParamInfo(_.a)
TreatMsg[TypeMessage2].getParamInfo(_.d)

So, how to get this wildcard working? I mean, I'd like that the "getParamInfo()" function accepts only properties from the class passed to TreatMsg. I have a solution that uses reflection, but I'd like to get rid of this reflection. Any idea?

Thank you!

Community
  • 1
  • 1
banduk
  • 107
  • 1
  • 7
  • Inheriting from case classes is deprecated. You could use a trait for CClass1 instead. – Christian May 07 '12 at 10:21
  • From which *value* do you want to use `_.c`? You only give a type. – Debilski May 07 '12 at 10:27
  • Actually, just want to get the name of "c" here, but I was wondering if it could be possible to use a sintaxe like this one that I mentioned. – banduk May 07 '12 at 11:35
  • I’m not sure I understand. Could you add some more code maybe. Eg. what should `useVariable` return. Currently, it is not clear what the function `_.c` should be called with, so I don’t think this syntax is going to work without changes. – Debilski May 07 '12 at 11:41
  • I changed the example to try clarify it – banduk May 07 '12 at 12:18

1 Answers1

1
def useVariable[RetVal](func: (T)=>RetVal) = //...
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
  • Now that you've clarifed your question, it's obvious that there's now way to get `variable.name` as you've specified in your example. The solution you're looking for is probably to pass a string to `useVariable` and use reflection to get its value. – Ken Bloom May 09 '12 at 12:32
  • Yes, that's it. But the approach you suggested does fit well to my complete use-case with some small changes. Thank you Ken – banduk May 10 '12 at 08:42