0

I'm trying to assign a different value for each actor to the variable "file" in example class using its object in class A.

    class A{

  var a1=new Array[example](2) 

  def starting()= {

    for(i <- 0 to 3){

      if(i==0){
        a1(i).file="L1.txt"; 
      }
      else if(i==1){
        a1(i).file="L2.txt";
      }

      a1(i).start

    }
  }
}


class example extends Actor {

  var file="default.txt"

  var Handle = new A

  def act()= {
    loop{
      var count=0
      react{
        //remaining code
    }
  }
 }

This is throwing a nullpointerexception corresponding to the lines :

for(i <- 0 to 3){

          if(i==0){
            a1(i).file="L1.txt"; 
          }

i'm a beginner in scala.. i somehow am unable to figure out the reason for this exception. Please help.

  • `loop{ var count=0 ...` creates new counter on each iteration. Use `var count=0; loop { ...` – senia Dec 12 '12 at 08:40

3 Answers3

4

var a1=new Array[example](2) creates new Array with 2 nulls, so a1(i) is null.

Use var a1 = IndexedSeq.fill(2){ new example }

Off topic:

There is Code Review for such things, but your code is not scala way. Try to rewrite it.

For example:

scala> import actors.Actor._
import actors.Actor._

scala> val as = for ( fileName <- Seq("L1.txt", "L2.txt") )
     |   yield actor {
     |     var count = 0
     |     loop {
     |       receive {
     |         case t =>
     |           count += 1
     |           println(fileName + " " + count + " " + t)
     |       }
     |     }
     |   }
as: Seq[scala.actors.Actor] = List(scala.actors.Actor$$anon$1@ef82188, scala.actors.Actor$$anon$1@44616f65)

scala> as.foreach{ _ ! 's }
L2.txt 1 's
L1.txt 1 's
Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129
1

Apart from what @senia already diagnosed, you are allocating an array of 2 elements, then trying to iterate through 4 elements of it:

for(i <- 0 to 3){

which is surely going to produce an ArrayIndexOutOfBoundsException once i becomes 2. Loop condition should be for(i <- 0 to 1) or for(i <- 0 until 2) for this to work. Although there are indeed better, more Scala-ish ways to implement this.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
0

probably the file "L1.txt" is not being located!

read this URL Read entire file in Scala?

Community
  • 1
  • 1