Antek
Antek

Reputation: 650

Generic pattern matching and type erasure

The goal is to write creator function, define what kind of message actor can receive, and match this kind of message inside actor. So i want to specify that my expected message is of type X (i know this type only when i call create function)

I have very simple code:

import akka.actor.Actor.Receive

def create[X]():Receive = {
  case msg:X =>
}

This code gives me the following error: "abstract type pattern X is unchecked since it is eliminated by erasure"

I know what is type erasure, but i can't find any solution for this problem.

Upvotes: 0

Views: 155

Answers (1)

Joe K
Joe K

Reputation: 18424

A ClassTag will pretty much handle this:

def create[X](implicit tag: ClassTag[X]): Receive = {
  case msg if msg.getClass == tag.runtimeClass =>
}

Note though that if your message type is itself affected by type erasure, this will fail. For instance, create[List[String]] will still accept a List[Int]. I don't think there's a way around this since that info is completely gone at runtime.

Upvotes: 1

Related Questions