I'm using Scala 2.10.4 with akka 2.3.4. I ran into a problem where type inference is not behaving the way I expected.
The code below illustrates an example of what I am experiencing. I have a case class which wraps messages with an id
named MyMessage
. It is parameterized with the type of the message. Then I have a payload named MyPayload
which contains a String
.
Within an actor (here I'm just using a regular object named MyObject
since the problem isn't particular to akka) I am pattern matching and calling a function that operates on my payload type MyPayload
.
package so
case class MyMessage[T](id:Long, payload:T)
case class MyPayload(s:String)
object MyObject {
def receive:PartialFunction[Any, Unit] = {
case m @ MyMessage(id, MyPayload(s)) =>
// Doesn't compile
processPayload(m)
// Compiles
processPayload(MyMessage(id, MyPayload(s)))
}
def processPayload(m:MyMessage[MyPayload]) = {
println(m)
}
}
For reasons I don't understand, pattern patching with @
and an unapplied case class doesn't infer the type parameter of MyMessage[T]
. In the code above, I would have expected that m
would have type MyMessage[MyPayload]
. However, when I compile, it believes that the type is MyMessage[Any]
.
[error] PatternMatch.scala:9: type mismatch;
[error] found : so.MyMessage[Any]
[error] required: so.MyMessage[so.MyPayload]
[error] Note: Any >: so.MyPayload, but class MyMessage is invariant in type T.
[error] You may wish to define T as -T instead. (SLS 4.5)
[error] processPayload(m)
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 1 s, completed Aug 19, 2014 12:08:04 PM
Is this expected behavior? If so, what have I misunderstood about type inference in Scala?
PartialFunction[MyMessage[MyPayload], Unit]
. but then, what's the point? :) – goralPartialFunction[Any, Unit]
because that is what an actor'sreceive:Receive
is typed as. – joescii