0

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 ?

3
  • 2
    Just as an aside: You should prefer the second approach, where the println() is on its own line, despite the fact you can make the first approach work with a semicolon. The second approach is more idiomatic and thus more readable. Commented Jan 24, 2023 at 8:59
  • 1
    @ashish See kotlinlang.org/docs/coding-conventions.html#indentation Commented Jan 24, 2023 at 9:04
  • yes. thanks for mentioning @Slaw I am used to format on save in my intellij for Java, but starting with Kotlin so getting into some basic issues. Commented Jan 24, 2023 at 9:05

1 Answer 1

2

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.

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.