0

I read the tutorials on how to write a for loop in scala but it doesn't seem to work.

object Main {
    def pascalTriangle(rows:Int):List[Int]= {
    var previousRow:List[Int] = Nil 
    var row:List[Int] = Nil
    for(i <- 1 to rows) {
        for( j <- 1 to i+1){
            if (j == 1 || j == i)
                row :+ 1
            else
                row :+ previousRow(j) + previousRow(j - 1)
            }
            previousRow = row
            println (row)
            row = Nil
        }
    }
     def main(args: Array[String]) {
        pascalTriangle(6)
     }
}

I keep getting a type mismatch error within the for loop's conditions.

1
  • 3
    you have a return type of List[Int]. but you are actually returning Unit. Commented May 23, 2014 at 3:59

1 Answer 1

1

Your method pascalTriangle is declared to return a List[int].

However, the last expression in the body of the method is your outer for-loop. This is the expression whose value will be returned by the method.

As for-loops (that don't use the yield keyword) evaluate to (): Unit, there is a type-mismatch with the expected return type (for-loops without yield are used only for side-effect).

If you wanted to, for example, return row, you would need to simply write 'row' at the end of the method, after the outer for-loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.