Is there anything wrong with my code

Is there anything wrong with my code

Here’s my code:

import util.Random
println((1 to 5).map(_ => Random.nextInt))

Here’s the error:

[error] ./Documents/VS Code/Randomnumberlist/Randomnumberlist.scala:2:1
[error] Illegal start of toplevel definition
[error] println((1 to 5).map(_ => Random.nextInt))
[error] ^^^^^^^
Error compiling project (Scala 3.6.3, JVM (23))
Compilation failed

Well, obviously there is or you wouldn’t get the error you got. If you want to play with code like that, you should probably be using Scastie which has a mode which does what you tried to do.

You can see exactly what you wrote working here:
Scastie - An interactive playground for Scala.

If you’d rather not depend on an online tool, it depends how you executed it. This isn’t a normal Scala file–you need an object with a main method, at a minimum. But there is a script mode in scala-cli (which is also scala if you have 3.6 and are trying to run the file using scala as a command); if you save your file as .sc and do scala-cli run, it will wrap the code in the appropriate way for the JVM and do what you want.

For example:

~/Code/scala/temp$ scala-cli run A.scala
Compiling project (Scala 3.6.3, JVM (17))
[error] ./A.scala:2:1
[error] Illegal start of toplevel definition
[error] println((1 to 5).map(_ => Random.nextInt))
[error] ^^^^^^^
Error compiling project (Scala 3.6.3, JVM (17))
Compilation failed
~/Code/scala/temp$ mv A.scala A.sc
~/Code/scala/temp$ scala-cli run A.sc
Compiling project (Scala 3.6.3, JVM (17))
Compiled project (Scala 3.6.3, JVM (17))
Vector(2126242071, -375641670, -392946654, -2018029152, -544726030)

The minimal wrapping you need for it to be a valid .scala file and to run the code (not in script mode) is shown here:

~/Code/scala/temp$ cat B.scala
import util.Random

object Main:
  def main(args: Array[String]): Unit =
    println((1 to 5).map(_ => Random.nextInt))

~/Code/scala/temp$ scala-cli run B.scala
Compiling project (Scala 3.6.3, JVM (17))
Compiled project (Scala 3.6.3, JVM (17))
Vector(-920095178, -74663704, -476828234, -1424034221, 1497006213)
3 Likes

Or like so:

import util.Random

@main
def whateverYouWantToCallIt =
  println((1 to 5).map(_ => Random.nextInt))
1 Like

It works now, thanks