Run Your First Scala Script
Write and run your first Scala script with hands-on steps, troubleshooting tips, and what to learn next in the Scala for Python Developers track.
Focus: run your first scala script
You've learned about Scala's potential, but every great journey starts with a single step — and in Scala, that step is running your first script. If you're a Python developer, you're used to python script.py just working. Scala, on the other hand, lives on the JVM and comes with its own tooling, which can feel like a roadblock before you've even written a line of code. This lesson strips away the complexity and shows you how to write and run your first Scala script with confidence, so you can focus on learning the language, not fighting the setup.
The problem this lesson solves
When you're coming from Python, the first hurdle isn't the syntax — it's the execution model. In Python, you write a file, run python hello.py, and get output. In Scala, you need to understand concepts like compilation, JVM bytecode, and build tools (like scala-cli or sbt) before you can see any output. This creates a frustrating gap between learning and doing.
The pain is real: you want to try a small snippet, but you're unsure which tool to use, how to set up the environment, or what error messages mean. There are dozens of tutorials that show Scala code but few that walk you through actually running it. The result is that many Python developers give up early, assuming Scala is too cumbersome. But it doesn't have to be that way.
This lesson solves that problem by giving you a simple, repeatable process for running a Scala script — from a one-liner to a small program with multiple functions. You'll learn the mental model behind the tools, the exact steps to run your first script, and how to troubleshoot the most common issues. By the end, you'll be ready to move on to the next lesson in this track with a solid foundation.
Core concept / mental model
When you run a Python script, the interpreter reads your code line by line and executes it on the fly. Scala is a compiled language that runs on the Java Virtual Machine (JVM). Here's the key difference:
- Python: Interpreter reads source code → executes directly.
- Scala: Compiler (
scalac) converts source code to JVM bytecode → JVM executes that bytecode.
This distinction is why the tools matter. But for scripting, you don't need to manually invoke the compiler every time. Instead, you use a script runner — like scala-cli — that handles the compilation and execution behind the scenes. Think of it like this:
Analogy: Python's
python file.pyis like a chef who reads a recipe and cooks immediately. Scala's script runner is like a sous-chef who first preps all ingredients (compiles) and then the main chef (JVM) cooks the dish.
In Scala, a script is simply a file containing top-level expressions that are executed in order. You don't need a main method for scripts — the runner provides one automatically. This is different from Scala applications, where you need a main method or an object extending App.
The tool you'll use most often for quick tasks is scala-cli. It's a modern, user-friendly command-line tool designed for scripting and experimentation — a perfect match for Python developers who are used to a quick feedback loop. It can also package your scripts as standalone applications later, making it a versatile companion.
The mental model to remember: You write Scala code → you use scala-cli to compile and run it → you see output. Just like python wraps interpretation, scala-cli wraps compilation and execution.
How it works step by step
When you run a Scala script, the sequence of events is:
- Source code: You create a
.scalafile containing top-level expressions. For example:
scala
println("Hello, Scala!")
-
Compilation: The
scala-clitool invokes the Scala compiler (scalac) on your file, producing JVM bytecode. This step also resolves any dependencies you've declared (e.g., external libraries). -
Execution: The JVM loads the generated bytecode and runs it. The output of your
printlnstatements appears in your terminal. -
Cleanup: After execution, temporary files are cleaned up (unless you ask to keep them). This is all transparent to you — you just see the output.
The key is that scala-cli wraps these steps into a single command: scala-cli run myscript.scala. It also caches compiled artifacts, so subsequent runs are faster — like Python's __pycache__ but for bytecode.
If you were to do this manually, you'd run scalac myscript.scala to compile, then scala Main to execute, but that's more painful and unnecessary for scripting. That's why scala-cli is your go-to.
Hands-on walkthrough
Let's get your hands dirty. First, ensure you have scala-cli installed. If not, the installation instructions are on the official website, but here are quick commands for common OSes:
- macOS/Linux:
curl -sSLf https://scala-cli.virtuslab.org/get | sh - Windows (PowerShell):
Invoke-Expression (Invoke-WebRequest -Uri https://scala-cli.virtuslab.org/get.ps1).Content
Now, create a file named hello.scala with the following content:
// hello.scala
println("Hello, Scala!")
val greeting = "Hello from Scala!"
println(greeting)
Then run it:
scala-cli run hello.scala
Expected output:
Hello, Scala!
Hello from Scala!
You've just run your first Scala script! Notice that you didn't need a main method — scala-cli handled it for you.
Now, let's make it more interactive. Create a script that sums two numbers:
// sum.scala
def add(a: Int, b: Int): Int = a + b
val result = add(5, 7)
println(s"The result is $result")
Run with:
scala-cli run sum.scala
Output:
The result is 12
But what about when you want to pass command-line arguments? In Python, you might use sys.argv. In Scala scripts, scala-cli provides a special args variable. Try this:
// args_demo.scala
println(s"Received arguments: ${args.mkString(", ")}")
Run with:
scala-cli run args_demo.scala -- first second third
Output:
Received arguments: first, second, third
Notice the -- separator: everything after it is passed to your script as arguments. This is a crucial detail for scripting.
Finally, let's combine functions and loops to see a more realistic script — computing Fibonacci numbers:
// fibonacci.scala
def fib(n: Int): Int = {
if (n <= 1) n
else fib(n - 1) + fib(n - 2)
}
(0 to 10).foreach { i =>
println(s"fib($i) = ${fib(i)}")
}
Run it:
scala-cli run fibonacci.scala
Expected output (truncated):
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
...
fib(10) = 55
You've just executed loops, functions, and string interpolation — all in your first Scala script! You're not just running code; you're writing idiomatic Scala.
Compare options / when to choose what
You have several ways to run Scala code. The main options are:
| Tool | Use case | Example | Pros | Cons |
|---|---|---|---|---|
scala-cli |
Scripting, quick prototyping, small projects | scala-cli run script.scala |
Easy to use, fast feedback, supports arguments, can compile to apps | Newer, less known than sbt |
sbt |
Full projects with dependencies, build configurations | sbt run |
Industry standard, powerful dependency management, incremental compilation | Overkill for scripts, steeper learning curve |
| Scala REPL | Immediate interactive session, testing a snippet | scala or scala-cli repl |
No file needed, great for exploratory testing | Not for full scripts, state persists unless reset |
| IDE (IntelliJ IDEA) | Full development with debugging and refactoring | Run button | Rich IDE features, error highlighting, debugging | Heavy, slower startup |
For a Python developer who wants to quickly test an idea, scala-cli is the closest to python script.py. It's lightweight and straightforward. If you're working on a larger application, you'll eventually want sbt, but for now, focus on scala-cli.
Pro tip: When you need to experiment with a single expression, use the REPL. For a multi-line script, use
scala-cli. For a full project, usesbt.
If you're in a CI environment, scala-cli can also compile your script to a JAR and run it, making it perfect for automated tasks.
Troubleshooting & edge cases
Here are common issues you'll encounter and how to fix them.
Error: scala-cli: command not found
Cause: Not installed or not in your PATH.
Fix: Reinstall or add it to your PATH. On Linux/macOS, the installer typically adds it to ~/.local/share/scalacli/bin; ensure that's in your PATH.
Error: Error: Could not find or load main class
Cause: This happens when you try to run with scala instead of scala-cli. The old scala command may not support scripts in the same way.
Fix: Use scala-cli run always. If you must use scala, ensure your script has an object with a main method.
Error: Not found: args
Cause: Using args outside of scala-cli run context — for example, in a plain IDE run.
Fix: In scripts, args is available only when run via scala-cli. Or define your own main method that takes Array[String].
Script runs but produces no output
Cause: Maybe your script has only variable declarations and no println. The values are computed but not displayed.
Fix: Add a println for each value you want to see. For example:
val x = 5
println(x)
Errors about type mismatch or missing types
Cause: Scala is strongly typed. Python would happily compute 1 + "one". Scala won't.
Fix: Ensure types match. Use String interpolation carefully. For example:
val message = "The answer is " + (6 * 7)
println(message) // works
But 6 * 7 is an Int, so you must concatenate with a string, not add a string to a number.
scala-cli is too slow to start
Cause: First run downloads compiler artifacts, which takes time. Fix: Be patient; subsequent runs are faster. Or use the REPL for instant feedback.
What you learned & what's next
You've successfully run your first Scala script! Let's recap what we covered:
- The core concept that Scala compiles to JVM bytecode, and
scala-climakes scripting as easy as Python. - A step-by-step process for writing and running scripts: create a
.scalafile, usescala-cli run. - Hands-on examples with variables, functions, loops, and command-line arguments.
- The options available:
scala-clifor scripts,sbtfor projects, REPL for experimentation, IDEs for serious development. - Troubleshooting common errors: missing commands,
argsnot found, type mismatches.
You've now mastered the essential skill of running Scala code, which unlocks everything else in this track. The next lesson will dive into Scala syntax for Python developers, where you'll see how familiar concepts like variables, conditionals, and loops map between the two languages. With your script-running foundation, you'll be able to experiment as you learn.
Key takeaway:
scala-cli run file.scalais your best friend for scripting in Scala. Embrace it and you'll feel right at home as a Python developer.
Practice recap
Create a script that reads a number from the command line and prints its factorial. Use scala-cli run factorial.scala -- 5 to execute it. You'll practice defining functions, using args, and converting strings to integers with toInt. This exercise solidifies the script-running workflow before moving to the next lesson.
Common mistakes
- Using
python file.scalainstead ofscala-cli run file.scala— they are not interchangeable. - Forgetting the
--separator before command-line arguments when usingscala-cli run. - Trying to use
argsin a script run outsidescala-cli(e.g., in an IDE) — it's not defined. - Writing a script with only variable definitions and no
println, expecting output—nothing gets printed. - Assuming Scala is dynamically typed like Python and mixing types in expressions (e.g.,
1 + "one").
Variations
- Use the Scala REPL (
scala-cli repl) for instant feedback on small snippets, like Python's interactive shell. - For larger projects, switch to
sbtwithsbt runto manage dependencies and build configurations. - Use an IDE like IntelliJ IDEA with the Scala plugin for a more structured development environment with debugging.
Real-world use cases
- Automating a data-processing pipeline where you need a small, compiled script that runs on a JVM environment.
- Creating a command-line utility in Scala for parsing JSON logs, leveraging libraries like
upicklewithscala-cli. - Prototyping a Scala function or algorithm before integrating it into a larger
sbtproject.
Key takeaways
- Scala is compiled to JVM bytecode;
scala-clihides the compilation step for scripts. - You run a Scala script with
scala-cli run filename.scala— no need for a main method. - Command-line arguments in scripts are accessed via
args, after a--separator. - The REPL is perfect for quick experiments, while
scala-cliis for full scripts. - Type safety means you must match types in expressions; catch common errors early.
- Troubleshooting: verify installation, use
scala-cli, addprintlnfor visible output.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.