Differences between Props(new A with B) and Props[

2019-08-31 12:22发布

问题:

I was trying to create a simple trait to intercept received messages from arbitrary actors, using the stackable trait pattern. But when creating the Props, it turns out that Props(new A with B) is different from Props[A with B]. Namely, the first variant works but not the second one. Where is the difference?

A minimal example: https://gist.github.com/ale64bit/df496ec2a43d0ec2ddb3

Thanks!

回答1:

I'm not sure of the exact reason behind the behavior, but it would appear that using the parameterized version does not know how to construct the request type and simply constructs the primary type. I.e. when you print out the actual class inside the actor you get

Props(new FooActor with Interceptor) => Main$$anonfun$1$$anon$1
Props[FooActor with Interceptor] => FooActor

My best guess is that the ClassTag or builder generated from the ClassTag does not understand the parameterized FooActor with Interceptor syntax. If you however create a new class that mixes these two before, it does work:

class FooActorWithInterceptor extends FooActor with Interceptor

Props[FooActorWithInterceptor] => FooActorWithInterceptor

As an aside, I've found from being bitten a number of times, that using the parametrized version of Props should be avoided. While it works for no-parameter constructor versions, should you ever add some parameters to the constructor Props[A] will not complain at compile time. Meanwhile Props(new A) will give you a compilation error.