Home > Back-end >  I received the error "error: expected class or object definition" in Scala
I received the error "error: expected class or object definition" in Scala

Time:11-18

I have the below code but I received the error: expected class or object definition. and it referenced to Val matrix. what is the problem?

object Main{
 def squaresHaveNoDuplicates(matrix: Array[Array[Int]]) = {
    val rowBlocks = matrix.grouped(3).toArray
    println(rowBlocks)
 }
}      

val matrix= Array(
Array(0, 5, 0, 3, 0, 9, 0, 2, 6),
Array(3, 8, 9, 4, 2, 0, 1, 5, 7),
Array(4, 0, 6, 1, 0, 0, 0, 8, 9),
Array(0, 1, 3, 7, 9, 8, 0, 0, 4),
Array(0, 0, 8, 0, 0, 0, 5, 0, 0),
Array(0, 6, 0, 0, 0, 3, 0, 0, 0),
Array(0, 0, 1, 9, 3, 0, 0, 4, 0),
Array(9, 3, 5, 6, 4, 0, 8, 0, 1),
Array(0, 0, 2, 8, 7, 0, 0, 0, 5)

squaresHaveNoDuplicates(matrix)

Edit: even i try a simple code like :

val str= Array(1,2,3)

I receive the same error in REPL.

CodePudding user response:

There are simple syntax errors.

object Main extends App {
  def squaresHaveNoDuplicates(matrix: Seq[Seq[Int]]) = {
    val rowBlocks = matrix.grouped(3).toSeq
    println(rowBlocks)
  }

  val matrix = Seq(
    Seq(0, 5, 0, 3, 0, 9, 0, 2, 6),
    Seq(3, 8, 9, 4, 2, 0, 1, 5, 7),
    Seq(4, 0, 6, 1, 0, 0, 0, 8, 9),
    Seq(0, 1, 3, 7, 9, 8, 0, 0, 4),
    Seq(0, 0, 8, 0, 0, 0, 5, 0, 0),
    Seq(0, 6, 0, 0, 0, 3, 0, 0, 0),
    Seq(0, 0, 1, 9, 3, 0, 0, 4, 0),
    Seq(9, 3, 5, 6, 4, 0, 8, 0, 1),
    Seq(0, 0, 2, 8, 7, 0, 0, 0, 5)
  )

  squaresHaveNoDuplicates(matrix)

}

  1. Code like value assignment, val matrix = Array(...), cannot be located outside of an class or object. Thus the error message.
  2. Missing parentheses for definition of the outer matrix: Array
  3. println won't print the content of an Array and I replaced it with Seq
  4. Main won't run unless it extends App or defines main method. JVM needs to have an entry point into the program and the convention is that this is a def main(arg: Array[String]). Scala App is using so called delayed initialization but it is phased out in Scala 3. Read more here
  • Related