Search code examples
javascalacqrsparameterized

Scala, reflection of a concrete implementation of a parameterized trait


I'm looking to see if there is any way of getting around type erasure in the following case:

I have a trait

trait IHandle[T <: ICommand] {
    def handle(command: T) : Unit
}

And I wish to find using reflection a concrete implementation of say

IHandle[MyCommand]

Which might looking something like

class MyCommandHandler(dependency:Dependency) extends IHandle[MyCommand] {
  def handle(command:MyCommand): Unit = ...
}

(I am playing around with creating a command dispatcher in a CQRS model, I'm more than happy to hear if this is the totally wrong approach to take in Scala and am open to suggestions)


Solution

  • You can using Manifest, but I strongly recommend to avoid using such thing in Scala... this is definitely the wrong approach IMO.

    Basically you need a registry (could be a Map[Manifest[_], IHandle[_]] where you store all implementation with there manifest, and you can then lookup in the registry.

    def store[T : Manifest](handle: Handle[T]) = map.put(manifest[T], handle)
    def lookup[T : Manifest] = map.get(manifest[T])
    
    // And then ...
    store(new Handle[Foo])
    lookup[Foo]
    

    A correct approach would probably imply the usage of typeclass (try to google for that), it's hard to really give you a complete solution without having the big picture of what you are doing... Even if I'm doing too some CQRS development on Scala.

    Don't hesitate to connect to #scala channel on freenode server to have a chat about that.