0

I have the following bit of code in scala which is not working:

 var tacTable : List[List[TACList]] = List(List())

  def gen(p: Program) = {
    for (i <- 0 to p.classes.length){
      for (j <- 0 to p.classes(i).methods.length){
        var tacInstr = new TACList()
        tacTable(i)(j) = tacInstr //error: application does not take parameters
      }
    }
  }

Apparently, it has to do with the fact that I'm using j to access the list and j is used in for...how can I solve this?

For convenience you can work with this other example which gives the same error:

var l : List[List[Int]] = List(List(1,2),List(3,4))
for (i <- 0 to l.length) {
  for (j <- 0 to l.length) {
    l(i)(j) = 8
  }
}  
2
  • 1
    Can you post a minimal reproducible example of your problem? Jan 1, 2017 at 13:20
  • 1
    Probably because List is immutable and you can't update it in place. Use a mutable.ListBuffer or something like that.
    – insan-e
    Jan 1, 2017 at 13:30

2 Answers 2

1

Lists are immutable. Try this instead:

 val tacTable  = p.classes.map { _.methods.map { _ =>
     new TACList()
 }
1

since I cannot comment on the initial post a sidenote here:

in a scala for-comprehension you can use multiple generators in a single for. so the nesting that you used is not necessary since you can use this:

for (i <- 0 to l.length; j <- 0 to l.length) {
  // your code
}

furthermore, this does not seem to apply in your case but if you had a flat mapped result you should use the yield of the for comprehension instead of a mutation in the body

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.