Scala
Online Scala Compiler
main.scala is compiled with Scala 3.10 and runs on Java 17, starting from an @main method or from object Main with def main. scala.io.StdIn.readLine() waits for you to type in the terminal.
Try it aboveHow Scala runs here
- Versions
- Scala 3.10 on Java 17
- Build
scalac main.scala- Run
java Main (the object with main)- Limits per run
- 512 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
A Scala 3 program that reads input
This main.scala uses an @main method and the braceless Scala 3 syntax to count words:
import scala.io.StdIn.readLine @main def run(): Unit = print("How many words? ") val n = readLine().trim.toInt val words = (1 to n).map { i => print(s"Word $i: ") readLine().trim.toLowerCase } val counts = words.groupBy(identity).view.mapValues(_.size).toList counts.sortBy((w, c) => (-c, w)).foreach((w, c) => println(s"$w: $c")) println(s"Longest: ${words.maxBy(_.length)}")
$ scalac main.scala && java run How many words? 4 Word 1: Kiwi Word 2: apple Word 3: kiwi Word 4: banana kiwi: 2 apple: 1 banana: 1 Longest: banana
Reading input in Scala
- readLine() returns the line as a String. Convert with .trim.toInt, or split it: readLine().split(" ").map(_.toInt).
- StdIn.readInt() reads a whole line and converts it, so 3 4 on one line throws NumberFormatException. Use readInt() only for one number per line.
- Iterating over io.Source.stdin.getLines() waits for the end of input, which this terminal never sends. Read a count first, or stop on an empty line.
What isn’t available here
- sbt, Mill and library dependencies: no cats, ZIO, Akka or circe. The Scala standard library and JDK 17 are there.
- More than one file: only main.scala is compiled, so keep all your classes and objects in it.
- A REPL. The whole file is compiled and run.
Errors you’ll see
- A Not found error for a name scalac can’t see: a typo, a missing import, or something defined in another file.
- “java.lang.NumberFormatException: For input string: "3 4"” toInt or readInt() got two numbers on one line. Split the line first.
- “No main method found: write an @main method, or object Main with def main(args: Array[String]).” The program compiled but has no entry point.
Questions
Which Scala version does this use?
Scala 3.10, compiled with scalac and run on Java 17.
Does Scala 2 code work?
Mostly. Scala 3 accepts braces, object Main with def main(args: Array[String]) and most Scala 2 code. A few Scala 2 features were dropped, so older code can need small changes.
How do I read input in Scala?
import scala.io.StdIn.readLine, then call readLine() for each line and type your answers in the terminal.