Home > Software design >  what is the kotlin nested loop syntax issue?
what is the kotlin nested loop syntax issue?

Time:01-24

I am getting error for this syntax

  for (i in 0 until 8) {
      for (j in 0 until 8) {

      } println()
  }

error is

For is not an expression, and only expressions are allowed here.

but this is valid

  for (i in 0 until 8) {
      for (j in 0 until 8) {

      }
      println()
  }

only thing I changed was where println() is called, I have worked with java so I thought that placement should not matter. What is the issue here ?

CodePudding user response:

I did some testing in Kotlin Playground. Kotlin compiler indeed cannot parse statements that are placed on the same line and not divided by ;.

For example 10 println("") will produce an error: "Unresolved reference: println". Note that 10 actually is an expression, since expressions are code blocks that produce single value.

The guessing is below:

The real question is, why Kotlin compiler shows the specific error, which is

For is not an expression, and only expressions are allowed here

I believe that has something to do with the Kotlin compiler's code parse algorithm. That seems like compiler tries to parse multiple statements on the same line as a single expression. for keyword makes it fail right away. However, if you replace for loop with a real expression, compiler will highlight the println call as something wrong, since it is something excess for an expression.

  • Related