I found a basic way to do this by manually passing the ClassTag. It is not
very pretty but it works:
import akka.actor._
import scala.reflect.ClassTag
class MyActor[V](size: Int, default: V, ct: ClassTag[V]) extends Actor {
// Array of given size filled with given default value
val array = Array.fill[V](size)(default)(ct)
override def receive: Receive = {
case i: Int if i < size && i >= 0 => println(array(i))
}
}
val system = ActorSystem("test")
val myActor = system.actorOf(Props(classOf[MyActor[Double]], 100, 0.0,
implicitly[ClassTag[Double]]))
myActor ! 3
// Correctly returns 0.0
On Friday, 9 October 2015 22:05:56 UTC+2, Rolf wrote:
>
> I wish to create an actor that stores an array of elements of some general
> type V. The typical way to instantiate such an array is to provide a
> ClassTag and default value. I have implemented this as follows:
>
> import akka.actor._
> import scala.reflect.ClassTag
>
> class MyActor[V : ClassTag](size: Int, default: V) extends Actor {
>
> // Array of given size filled with given default value
> val array = Array.fill[V](size)(default)
>
> override def receive: Receive = {
> case i: Int if i < size && i >= 0 => println(i)
> }
> }
>
> val system = ActorSystem("test")
> val myActor = system.actorOf(Props(classOf[MyActor[Double]], 100, 0.0))
> // java.lang.IllegalArgumentException: no matching constructor found on
> class MyActor for arguments [class java.lang.Integer, class
> java.lang.Double]
> // at akka.util.Reflect$.error$1(Reflect.scala:81)
> // ...
>
> Unfortunately, the above code does not work and I get an exception as soon
> as the actor is created. It seems that Akka does not pass the implicit
> class tag that is necessary to instantiate the class(?) Note that there is
> no problem when using the above pattern in a normal class:
>
> import scala.reflect.ClassTag
>
> class Test[V : ClassTag](size: Int, default: V) {
>
> // Array of given size filled with given default value
> val array = Array.fill[V](size)(default)
>
> }
>
> val test = new Test[Double](100, 0.0)
> test.array(3)
> // Correctly returns 0.0
>
> Any advice on how to get something like this working in Akka?
>
> Thanks!
>
--
>>>>>>>>>> Read the docs: http://akka.io/docs/
>>>>>>>>>> Check the FAQ:
>>>>>>>>>> http://doc.akka.io/docs/akka/current/additional/faq.html
>>>>>>>>>> Search the archives: https://groups.google.com/group/akka-user
---
You received this message because you are subscribed to the Google Groups "Akka
User List" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/akka-user.
For more options, visit https://groups.google.com/d/optout.