Create A Scala Project With sbt In The Command Line

Installation

  1. Java 8 JDK javac -version

  2. install sbt

Create a project

1
2
$ mkdir practice && cd practice
$ sbt new scala/hello-world.g8      # pull template from GitHub
1
2
3
4
5
6
7
8
- hello-world
    - project (sbt uses this to install manage plugins and dependencies)
        - build.properties
    - src
        - main
            - scala (All of your scala code goes here)
                -Main.scala (Entry point of program) 
    build.sbt (sbt's build definition file)
1
2
3
$ cd hello-world
$ sbt                            # open sbt console
$ ~run                           # ~ causes sbt to re-run on every file save

modify the src/main/scala/Main.scala file and see the results in the console.

add a dependency to the build.sbt

1
libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.1.0"

Testing Scala Code With sbt In The Command Line

One testing methodologies from the ScalaTest framework called FunSuite.

1
2
3
$ mkdir practice && cd practice
$ sbt new scala/scalatest-example.g8    # pull template from GitHub
$ cd ScalaTestTutorial
1
$ cat build.sbt
1
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test
1
$ cat src/main/scala/CubeCalculator.scala
1
2
3
4
5
object CubeCalculator extends App {
  def cube(x: Int) = {
    x * x * x
  }
}
1
$ cat src/main/scala/CubeCalculatorTest.scala
1
2
3
4
5
6
7
import org.scalatest.FunSuite

class CubeCalculatorTest extends FunSuite {
    test("CubeCalculator.cube") {
        assert(CubeCalculator.cube(3) === 27)
    }
}

test is function that comes from FunSuite that collects results from assertions within the function body.

"CubeCalculator.cube" is a name for the test. You can call it anything but one convention is “ClassName.methodName”.

The === is part of ScalaTest.

1
$ sbt test                                 # run the test suite