Skip to content

Files

Latest commit

bc18a05 · Oct 16, 2024

History

History
372 lines (288 loc) · 15.8 KB

install-scala.md

File metadata and controls

372 lines (288 loc) · 15.8 KB
layout title partof languages includeTOC newcomer_resources redirect_from
singlepage-overview
Getting Started
getting-started
fr
ja
ru
uk
true
title description icon link
Are You Coming From Java?
What you should know to get to speed with Scala after your initial setup.
fa fa-coffee
/tutorials/scala-for-java-programmers.html
title description icon link
Scala in the Browser
To start experimenting with Scala right away, use "Scastie" in your browser.
fa fa-cloud
/getting-started.html
/scala3/getting-started.html

The instructions below cover both Scala 2 and Scala 3.

{% altDetails need-help-info-box 'Need Help?' class=help-info %} *If you are having trouble with setting up Scala, feel free to ask for help in the `#scala-users` channel of [our Discord](https://discord.com/invite/scala).* {% endaltDetails %}

Resources For Newcomers

{% include inner-documentation-sections.html links=page.newcomer_resources %}

Install Scala on your computer

Installing Scala means installing various command-line tools such as the Scala compiler and build tools. We recommend using the Scala installer tool "Coursier" that automatically installs all the requirements, but you can still manually install each tool.

Using the Scala Installer (recommended way)

The Scala installer is a tool named Coursier, whose main command is named cs. It ensures that a JVM and standard Scala tools are installed on your system. Install it on your system with the following instructions.

{% tabs install-cs-setup-tabs class=platform-os-options %}

{% tab macOS for=install-cs-setup-tabs %} Run the following command in your terminal, following the on-screen instructions: {% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.macOS-brew %} {% altDetails cs-setup-macos-nobrew "Alternatively, if you don't use Homebrew:" %} On the Apple Silicon (M1, M2, …) architecture: {% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.macOS-arm64 %} Otherwise, on the x86-64 architecture: {% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.macOS-x86-64 %} {% endaltDetails %} {% endtab %}

{% tab Linux for=install-cs-setup-tabs %} Run the following command in your terminal, following the on-screen instructions.

On the x86-64 architecture: {% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.linux-x86-64 %} Otherwise, on the ARM64 architecture: {% include code-snippet.html language='bash' codeSnippet=site.data.setup-scala.linux-arm64 %} {% endtab %}

{% tab Windows for=install-cs-setup-tabs %} Download and execute the Scala installer for Windows based on Coursier, and follow the on-screen instructions. {% endtab %}

{% tab Other for=install-cs-setup-tabs defaultTab %}

JavaScript is disabled, click the tab relevant for your OS.

Follow the documentation from Coursier on how to install and run cs setup. {% endtab %}

{% endtabs %}

   You may need to restart your terminal, log out, or reboot in order for the changes to take effect. {: .help-info}

{% altDetails testing-your-setup 'Testing your setup' %} Check your setup with the command scala -version, which should output:

$ scala -version
Scala code runner version: 1.4.3
Scala version (default): {{site.scala-3-version}}

{% endaltDetails %}

Along with managing JVMs, cs setup also installs useful command-line tools:

Commands Description
scalac the Scala compiler
scala, scala-cli Scala CLI, interactive toolkit for Scala
sbt, sbtn The sbt build tool
amm Ammonite is an enhanced REPL
scalafmt Scalafmt is the Scala code formatter

For more information about cs, read coursier-cli documentation.

cs setup installs the Scala 3 compiler and runner by default (the scalac and scala commands, respectively). Whether you intend to use Scala 2 or 3, this is usually not an issue because most projects use a build tool that will use the correct version of Scala irrespective of the one installed "globally". Nevertheless, you can always launch a specific version of Scala using

$ cs launch scala:{{ site.scala-version }}
$ cs launch scalac:{{ site.scala-version }}

If you prefer Scala 2 to be run by default, you can force that version to be installed with:

$ cs install scala:{{ site.scala-version }} scalac:{{ site.scala-version }}

...or manually

You only need two tools to compile, run, test, and package a Scala project: Java 8 or 11, and sbt. To install them manually:

  1. if you don't have Java 8 or 11 installed, download Java from Oracle Java 8, Oracle Java 11, or AdoptOpenJDK 8/11. Refer to JDK Compatibility for Scala/Java compatibility detail.
  2. Install sbt

Using the Scala CLI

In a directory of your choice, which we will call <project-dir>, create a file named hello.scala with the following code:

//> using scala {{site.scala-3-version}}

@main
def hello(): Unit =
  println("Hello, World!")

You can define a method with the def keyword and mark it as a "main" method with the @main annotation, designating it as the entry point in program execution. The method's type is Unit, which means it does not return a value. Unit can be thought of as an analogue to the void keyword found in other languages. The println method will print the "Hello, World!" string to standard output.

To run the program, execute scala run hello.scala command from a terminal, within the <project-dir> directory. The file will be compiled and executed, with console output similar to following:

$ scala run hello.scala             
Compiling project (Scala {{site.scala-3-version}}, JVM (20))
Compiled project (Scala {{site.scala-3-version}}, JVM (20))
Hello, World!

Handling command-line arguments

Rewrite the hello.scala file so that the program greets the person running it.

//> using scala {{site.scala-3-version}}

@main
def hello(name: String): Unit =
  println(s"Hello, $name!")

The name argument is expected to be provided when executing the program, and if it's not found, the execution will fail. The println method receives an interpolated string, as indicated by the s letter preceding its content. $name will be substituted by the content of the name argument.

To pass the arguments when executing the program, put them after --:

$ scala run hello.scala -- Gabriel          
Compiling project (Scala {{site.scala-3-version}}, JVM (20))
Compiled project (Scala {{site.scala-3-version}}, JVM (20))
Hello, Gabriel!

You can read more about main methods and string interpolation in the Scala Book.

Adding dependencies

We now write a program that will count the files and directories present in its working directory. We use the os-lib library from the Scala toolkit for that purpose. A dependency on the library can be added with the //> using directive. Put the following code in counter.scala.

//> using scala {{site.scala-3-version}}
//> using dep "com.lihaoyi::os-lib:0.10.7"

@main
def countFiles(): Unit =
  val paths = os.list(os.pwd)
  println(paths.length)

In the code above, os.pwd returns the current working directory. We pass it to os.list, which returns a sequence of paths directly within the directory passed as an argument. We use a val to declare an immutable value, in this example storing the sequence of paths.

Execute the program. The dependency will be automatically downloaded. The execution should result in a similar output:

$ scala run counter.scala       
Compiling project (Scala {{site.scala-3-version}}, JVM (20))
Compiled project (Scala {{site.scala-3-version}}, JVM (20))
4

The printed number should be 4: hello.scala, counter.scala and two hidden directories created automatically when a program is executed: .bsp containing information about project used by IDEs, and .scala-build containing the results of compilation.

As it turns out, the os-lib library is a part of Scala Toolkit, a collection of libraries recommended for tasks like testing, operating system interaction or handling JSONs. You can read more about the libraries included in the toolkit here. To include the toolkit libraries, use the //> using toolkit 0.5.0 directive:

//> using scala {{site.scala-3-version}}
//> using toolkit 0.5.0

@main
def countFiles(): Unit =
  val paths = os.list(os.pwd)
  println(paths.length)

This program is identical to the one above. However, other toolkit libraries will also be available to use, should you need them.

Using the REPL

You can execute code interactively using the REPL provided by the scala command. Execute scala in the console without any arguments.

$ scala
Welcome to Scala {{site.scala-3-version}} (20-ea, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
                                                                                                                                                                            
scala> 

Write a line of code to be executed and press enter.

scala> println("Hello, World!")
Hello, World!
                                                                                                                                                                            
scala> 

The result will be printed immediately after executing the line. You can declare values:

scala> val i = 1
val i: Int = 1
                                                                                                                                                                            
scala> 

A new value of type Int has been created. If you provide an expression that can be evaluated, its result will be stored in an automatically created value.

scala> i + 3
val res0: Int = 4
                                                                                                                                                                            
scala> 

You can exit the REPL with :exit.

Next steps

Now that you have tasted a little bit of Scala, you can either explore the language itself, or learn how to set up a project using the sbt and an IDE using the tutorials below. If you want to familiarize yourself with the language more, consider checking out:

Create a "Hello World" project with sbt

Once you have installed sbt, you are ready to create a Scala project, which is explained in the following sections.

To create a project, you can either use the command line or an IDE. If you are familiar with the command line, we recommend that approach.

Using the command line

sbt is a build tool for Scala. sbt compiles, runs, and tests your Scala code. (It can also publish libraries and do many other tasks.)

To create a new Scala project with sbt:

  1. cd to an empty folder.
  2. Run the command sbt new scala/scala3.g8 to create a Scala 3 project, or sbt new scala/hello-world.g8 to create a Scala 2 project. This pulls a project template from GitHub. It will also create a target folder, which you can ignore.
  3. When prompted, name the application hello-world. This will create a project called "hello-world".
  4. Let's take a look at what just got generated:
- hello-world
    - project (sbt uses this for its own files)
        - build.properties
    - build.sbt (sbt's build definition file)
    - src
        - main
            - scala (all of your Scala code goes here)
                - Main.scala (Entry point of program) <-- this is all we need for now

More documentation about sbt can be found in the Scala Book (see here for the Scala 2 version) and in the official sbt documentation

With an IDE

You can read a short summary of Scala IDEs on a dedicated page

Open hello-world project

Let's use an IDE to open the project. The most popular ones are IntelliJ and VSCode. They both offer rich IDE features, but you can still use many other editors.

Using IntelliJ

  1. Download and install IntelliJ Community Edition
  2. Install the Scala plugin by following the instructions on how to install IntelliJ plugins
  3. Open the build.sbt file then choose Open as a project

Using VSCode with metals

  1. Download VSCode
  2. Install the Metals extension from the Marketplace
  3. Next, open the directory containing a build.sbt file (this should be the directory hello-world if you followed the previous instructions). When prompted to do so, select Import build.

Play with the source code

View these two files in your IDE:

  • build.sbt
  • src/main/scala/Main.scala

When you run your project in the next step, the configuration in build.sbt will be used to run the code in src/main/scala/Main.scala.

Run Hello World

If you’re comfortable using your IDE, you can run the code in Main.scala from your IDE.

Otherwise, you can run the application from a terminal with these steps:

  1. cd into hello-world.
  2. Run sbt. This opens up the sbt console.
  3. Type ~run. The ~ is optional and causes sbt to re-run on every file save, allowing for a fast edit/run/debug cycle. sbt will also generate a target directory which you can ignore.

When you’re finished experimenting with this project, press [Enter] to interrupt the run command. Then type exit or press [Ctrl+D] to exit sbt and return to your command line prompt.

Getting Help

There are a multitude of mailing lists and real-time chat rooms in case you want to quickly connect with other Scala users. Check out our community page for a list of these resources, and for where to reach out for help.