Scala : First project - Hello World

·

2 min read

create first project

Using the command line to create first project
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:

  • cd to an empty folder.
  • 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.
  • When prompted, name the application HelloWorld.
    This will create a project called “helloworld”. Seems it change the letter automaticlly.

Let’s take a look at what just got generated:

scala_firstproject_3.png

  • helloworld
    • project (sbt uses this for its own files)
    • 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
      • test
        • scala
          • Mysuite.scala

run first project

run the application from a terminal with these steps:

  1. cd into hello-world.
  2. Run sbt. This opens up the sbt console.

scala-helloworld-1.png 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.

scala-helloworld-2.png

4.You can see the "Hello World" message.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.
scala-helloworld-3.png

with an IDE

You can choose multiple IDE to edit Scala program. I use VS Code.
Open VS code, go to Extensions, search and install "Metals".
image.png Metals is a “Scala language server” that provides support for writing Scala code in VS Code and other editors like Atom, Sublime Text, and more, using the Language Server Protocol.
Under the hood, Metals communicates with the build tool by using the Build Server Protocol (BSP). For details on how Metals works, see, “Write Scala in VS Code, Vim, Emacs, Atom and Sublime Text with Metals”.

Then open the project folder. You can see two files.

build.sbt
src/man/scala/Main.scala

image.png Main.scala stores your source code.

image.png build.sbt stroes the configuration for run the source code.

Resources:

docs.scala-lang.org/getting-started/index.h..