The ecosystem
The standard library is enough for a program that talks to files and sockets, and most production Scala is written on top of a small number of libraries that add what the library leaves out. This lesson describes the six a reader meets first. None of them is downloaded here: a dependency outside the ones a course pins has to come from a repository, and a run without a network stops at the download, so each example below is a fragment of the shape a program has and is marked as not run.
Effects: Cats Effect and ZIO
Future starts its work as soon as it is created, which makes a pipeline hard to reason about: the value is already running while the code is still being assembled. A modern effect library describes the work first and runs it at the edge of the program, so a failure is a value, a retry is a combinator and a test can run an effect without a thread. Cats Effect is that layer for the Typelevel ecosystem, built on IO:
cats.scala
//> using dep org.typelevel::cats-effect::3.6.3
import cats.effect.IO
import cats.effect.unsafe.implicits.global
val program: IO[Unit] =
for
_ <- IO.println("first")
_ <- IO.println("second")
yield ()
program.unsafeRunSync()
scala-cli run --server=false cats.scala
not run in this environment
ZIO is the same idea with the error and the environment in the type: ZIO[R, E, A] reads a value of type A, may fail with E, and needs an environment R. A large application that passes a database and a configuration through the environment gets them from the type rather than from a parameter list:
zio.scala
//> using dep dev.zio::zio::2.1.16
import zio.*
val program: ZIO[Any, Nothing, Unit] =
for
_ <- Console.printLine("first")
_ <- Console.printLine("second")
yield ()
Unsafe.unsafe(implicit u => Runtime.default.unsafe.run(program))
scala-cli run --server=false zio.scala
not run in this environment
Concurrency and data: Pekko and Spark
Pekko is the Apache continuation of Akka: an actor is a small object with a mailbox that handles one message at a time, so shared mutable state never crosses a thread. The typed API describes the messages a behavior accepts:
pekko.scala
//> using dep org.apache.pekko::pekko-actor-typed::1.1.3
import org.apache.pekko.actor.typed.{ActorSystem, Behavior}
import org.apache.pekko.actor.typed.scaladsl.Behaviors
val behavior: Behavior[String] = Behaviors.receiveMessage { message =>
println(s"received $message")
Behaviors.same
}
val system = ActorSystem(behavior, "demo")
scala-cli run --server=false pekko.scala
not run in this environment
Spark is the batch engine that made Scala known outside the JVM community: a driver builds a plan over distributed data, and the cluster runs it. The local mode runs the same plan in one JVM, which is why the example below needs nothing but the library:
spark.scala
//> using dep org.apache.spark::spark-sql::4.0.0
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder().master("local[1]").getOrCreate()
val frame = spark.createDataFrame(List(("Ada", 36), ("Grace", 45))).toDF("name", "age")
frame.show()
scala-cli run --server=false spark.scala
not run in this environment
The web: http4s and Circe
http4s is an HTTP server and client as a function from a request to an effectful response: a route is a pattern match, and the server is a resource that the effect system starts and stops. Circe is the JSON library beside it: a codec turns a case class into JSON and back, and for a plain case class the compiler derives the codec:
http4s.scala
//> using dep org.http4s::http4s-ember-server::0.23.30
import cats.effect.IO
import org.http4s.HttpRoutes
import org.http4s.dsl.io.*
import org.http4s.ember.server.EmberServerBuilder
val routes = HttpRoutes.of[IO] { case GET -> Root / "hello" => Ok("Hello") }
EmberServerBuilder.default[IO].withHttpApp(routes.orNotFound).build.useForever
scala-cli run --server=false http4s.scala
not run in this environment
circe.scala
//> using dep io.circe::circe-generic::0.14.10
import io.circe.generic.auto.*
import io.circe.syntax.*
case class User(name: String, age: Int)
val user = User("Ada", 36)
println(user.asJson.noSpaces)
scala-cli run --server=false circe.scala
not run in this environment
The list is not a ranking. A program that needs one HTTP call takes java.net.http.HttpClient and no library at all; a service with a database, a configuration and a dozen endpoints takes a stack, and the stack is a decision about how the team wants to describe failure and time. What each library asks of a reader is the same first step: an effect type, a given for the runtime, and a program that is a value until the edge runs it.
Related
- Future and Promise: the effect type of the standard library, and what these libraries replace.
- The HTTP client: an HTTP call with no library at all.
- Type classes: the mechanism a JSON codec and an effect runtime are built on.
- Derives: the one word that writes the Circe codec of a case class.
Article author: Arthur Isaev