Hello World in Scala
Your first Scala program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first Scala program and explore the elegance of this JVM language.
The Code
Create a file named HelloWorld.scala:
| |
Understanding the Code
object HelloWorld- Defines a singleton object, Scala’s way of creating static members and entry points.def main(args: Array[String]): Unit- The entry point method.Unitis Scala’s equivalent to Java’svoid.println()- A built-in function that prints to the console with a newline.
Scala’s Object-Oriented Twist
Unlike Java, Scala uses object instead of static. An object is a singleton instance—there’s exactly one HelloWorld in memory. This is more elegant than Java’s class-with-static-methods approach.
Running with Docker
The easiest way to run this without installing Scala locally:
| |
Running Locally
If you have Scala installed:
| |
Expected Output
Hello, World!
Alternative: Even More Concise
Scala also supports a top-level script style (Scala 3):
| |
Or using the new Scala 3 syntax without braces:
| |
These modern approaches use the @main annotation to designate the entry point, eliminating the need for an object wrapper.
Key Concepts
- JVM Language - Scala compiles to Java bytecode and runs on the JVM
- Object vs Class - Scala uses singleton objects for static-like functionality
- Type Inference - While we specified types here, Scala can often infer them
- Concise Syntax - Scala reduces boilerplate compared to Java
- Script Mode - Scala files can be run directly without explicit compilation
Scala vs Java
Compare this Scala version to the Java equivalent:
Java:
| |
Scala:
| |
Notice the differences:
- No
publickeyword needed (public by default) objectinstead ofclasswithstaticdeffor method definitions- No semicolons required
printlnis a top-level function, notSystem.out.println
What Makes Scala Special?
Even in this simple example, we see Scala’s philosophy:
- Concise but clear: Less ceremony than Java
- Hybrid paradigm: Object-oriented (singleton object) meets functional (first-class functions)
- JVM compatibility: Full access to Java libraries
- Modern features: Script mode, type inference, and optional syntax
Next Steps
Continue to explore Scala’s powerful features:
- Variables and immutability (
valvsvar) - Collections and functional operations
- Pattern matching
- Higher-order functions
- Type inference and type safety
Scala scales from simple scripts like this to massive distributed systems, making it a truly “scalable language.”
Running Today
All examples can be run using Docker:
docker pull williamyeh/scala:latest