Horje
How to add Dependency in Scala?

Scala, a strong language that unites both object-oriented and functional programming techniques has to depend on external libraries to enhance its capabilities. To develop projects seamlessly, there must be efficient handling of these libraries. This is where dependency management becomes important. In this article, we will see the process of adding Scala dependencies with examples and step-by-step procedures.

Setting Up the Environment

To work with Scala, you need to set up your development environment. Ensure you have Scala installed and a build tool like SBT (Scala Build Tool).

1. Create a New Project Using SBT

sbt new scala/scala-seed.g8

Inside your project directory, there is a build.sbt file. This file will contain your project’s configuration, including dependencies.

Creating a Scala Project

Creating a Scala Project

2. Define Your Project in build.sbt

Open build.sbt and define your project settings.

Example:

name := “MyScalaProject”,
version := “0.1”,
scalaVersion := “2.13.6”,

3. Add Dependencies

Dependencies are added under the libraryDependencies setting.

For example, to add the popular JSON library play-json, your build.sbt might look like this:

lazy val root = (project in file(“.”))
.settings(
name := “MyScalaProject”,
version := “0.1”,
scalaVersion := “2.13.6”,
libraryDependencies += munit % Test,
libraryDependencies += “com.typesafe.play” %% “play-json” % “2.9.2”
)

Adding Dependencies

Adding Dependencies

4. Fetch and Use Dependencies

Once you have defined your dependencies, you need to fetch them.

Run the following command in your project directory:

sbt update

Updating Project

Updating Project

5. Run Your Project

Run the following command in your project directory:

sbt run

Running Scala Project

Running Scala Project

Example 1: Adding Akka HTTP

1. Adding Akka HTTP Dependencies

libraryDependencies += “com.typesafe.akka” %% “akka-http” % “10.2.7”,
libraryDependencies += “com.typesafe.akka” %% “akka-actor-typed” % “2.6.19”,
libraryDependencies += “com.typesafe.akka” %% “akka-stream” % “2.6.19”

2. Complete build.sbt

import Dependencies._

ThisBuild / scalaVersion := “2.13.12”
ThisBuild / version := “0.1.0-SNAPSHOT”
ThisBuild / organization := “com.example”
ThisBuild / organizationName := “example”

lazy val root = (project in file(“.”))
.settings(
name := “MyScalaProject”,
version := “0.1”,
scalaVersion := “2.13.9”,
libraryDependencies += munit % Test,
libraryDependencies += “com.typesafe.akka” %% “akka-http” % “10.2.7”,
libraryDependencies += “com.typesafe.akka” %% “akka-actor-typed” % “2.6.19”,
libraryDependencies += “com.typesafe.akka” %% “akka-stream” % “2.6.19”
)

3. Implementation Code

Scala
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._

object Example1 extends App {
  implicit val system = ActorSystem("my-system")
  implicit val executionContext = system.dispatcher

  val route = path("hello") {
    get {
      complete("Hello, Akka HTTP!")
    }
  }

  Http().newServerAt("localhost", 8080).bind(route)
}

Output:

Running Scala Akka HTTP

Running Scala Akka HTTP

Example #2 Adding ScalaTest

1. Adding ScalaTest Dependencies

libraryDependencies += “org.scalatest” %% “scalatest” % “3.2.16” % Test

2. Complete build.sbt

import Dependencies._

ThisBuild / scalaVersion := “2.13.12”
ThisBuild / version := “0.1.0-SNAPSHOT”
ThisBuild / organization := “com.example”
ThisBuild / organizationName := “example”

lazy val root = (project in file(“.”))
.settings(
name := “MyScalaProject”,
version := “0.1”,
scalaVersion := “2.13.9”,
libraryDependencies += munit % Test,
libraryDependencies += “org.scalatest” %% “scalatest” % “3.2.16” % Test
)

3. Test Implementation Code

Scala
package example

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class Test2 extends AnyFlatSpec with Matchers {
  "A String" should "have the correct length" in {
    "Scala".length shouldEqual 5
  }
}

Output:

Running Scala Test

Running Scala Test

Example #3 Adding scala-csv Library

1. Adding scala-csv Dependencies

libraryDependencies += “com.github.tototoshi” %% “scala-csv” % “1.3.10”

2. Complete build.sbt

import Dependencies._

ThisBuild / scalaVersion := “2.13.12”
ThisBuild / version := “0.1.0-SNAPSHOT”
ThisBuild / organization := “com.example”
ThisBuild / organizationName := “example”

lazy val root = (project in file(“.”))
.settings(
name := “CsvWork”,
libraryDependencies += munit % Test,
libraryDependencies += “com.github.tototoshi” %% “scala-csv” % “1.3.10”
)

3. Implementation Code

Scala
import scala.io.Source

object Example3 {
  def main(args: Array[String]): Unit = {
    val filename = "data.csv"
    val delimiter = ","
    val file = Source.fromFile(filename)
    for (line <- file.getLines()) {
        val fields = line.split(delimiter).map(_.trim)
        println(fields.mkString(", "))
    }
    file.close()
  }
}

Output:

Running Scala CSV

Running Scala CSV

Conclusion

It is easy to add dependencies in Scala particularly if you are working with sbt. By defining dependencies in the build.sbt file, you can easily manage and use external libraries, enhancing your project’s capabilities and efficiency. You should be confident with adding and utilizing these kinds of stuffs into your scala jobs using the examples provided.

FAQ’s related to How to add Dependency in Scala?

1. What does a dependency mean in Scala?

A dependency on Scala is any form of an external library or module that a project has to possess for it to run well.

2. What is sbt and its significance in Scala?

Simple Build Tool (SBT) is widely applied as a deployment tool in coding operations such as compilation, dependencies management, packaging apps among others.

3. How do I add a dependency in sbt?

The process of adding a dependence on sbt involves including it under libraryDependencies within your build.sbt file.

4. Where do we get our Scala dependencies from?

These Scala dependencies are kept mostly in Maven Central and repositories belonging to scala itself.

5. Can I use other build tools apart from sbt?

Other alternative build tools for managing scala dependences include; Maven and Gradle. However, when it comes to scala projects most people prefer using sbt since it is the commonest one.




Reffered: https://www.geeksforgeeks.org


Scala

Related
How to Read and Write CSV File in Scala? How to Read and Write CSV File in Scala?
Scala AnyRef type Scala AnyRef type
How to Convert RDD to Dataframe in Spark Scala? How to Convert RDD to Dataframe in Spark Scala?
What are All the Uses of an Underscore in Scala? What are All the Uses of an Underscore in Scala?
How to go To and From Java Collections in Scala? How to go To and From Java Collections in Scala?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13