Scala JVM functional-OO language
Light · Postcard
102 × 152 mm · PDF
Dark · Postcard
102 × 152 mm · PDF
Ink saver · Postcard
102 × 152 mm · PDF
Light · A4 landscape
297 × 210 mm · PDF
Dark · A4 landscape
297 × 210 mm · PDF
Ink saver · A4 landscape
297 × 210 mm · PDF
Light · A3 landscape
420 × 297 mm · PDF
Dark · A3 landscape
420 × 297 mm · PDF
Ink saver · A3 landscape
420 × 297 mm · PDF
Start here
val x = 1def f(a: Int): Int = a * 2
case class P(name: String)
x matchfor x <- xs yield f(x)
enum Color: case Red, Green
@main def run() = println("hi")
scala-cli run <file>
Concepts
Values and methods
val x: Int = 1var n = 0def add(a: Int, b: Int): Int = a + b
def greet(name: String = "you") = s"Hi
$name"
(a: Int) => a + 1
xs.map(_ * 2)if x > 0 then "pos" else "neg"
@main def run() = println("hi")
Classes and traits
class Dog(name: String)
case class Point(x: Int, y: Int)
p.copy(x = 5)trait Speaker: def speak(): String
class Dog extends Speaker, Runner
object Util: def one = 1
enum Color: case Red, Green, Blue
enum Opt: case No; case Yes(v: Int)
sealed trait Shape
extension (s: String) def shout = s.toUpperCase
given Ordering[P] = Ordering.by(_.x)
def sorted[T](xs: List[T])(using Ordering[T])
Pattern matching
x match case 1 => "one"; case _ =>
"other"
case Point(0, y) =>
case n if n > 0 =>
case h :: t =>
case Some(v) => ; case None =>
Collections
List(1, 2, 3)Map("a" -> 1)
xs.map(f)xs.filter(p)xs.flatMap(f)xs.foldLeft(0)(_ + _)
xs.sortBy(_.age)
xs.groupBy(_.k)m.getOrElse(k, 0)
scala.collection.mutable.ArrayBuffer[Int]()
xs.collect { case Some(v) => v }
Options, Either, for
Option(x)opt.map(f).getOrElse(d)
Right(v) / Left(err)
for x <- xs yield f(x)
for x <- xs; y <- ys if x < y yield (x, y)
for a <- optA; b <- optB yield a + b
for x <- xs do println(x)
s"$a and ${a + 1}"
scala-cli
scala-cli run <file>.scala
scala-cli replscala-cli test .
scala-cli setup-ide .
//> using dep org::name:1.0
Recipes
//> using scala 3.3.4//> using dep com.lihaoyi::os-lib:0.10.0@main def run() = println(os.pwd)
enum Expr: case Num(n: Int) case Add(a: Expr, b: Expr)def eval(e: Expr): Int = e match case Expr.Num(n) => n case Expr.Add(a, b) => eval(a) + eval(b)
trait Show[A]: def show(a: A): Stringgiven Show[Int] = _.toStringdef out[A](a: A)(using s: Show[A]) = s.show(a)
scala.io.Source.fromFile("f.txt").getLines .flatMap(_.split("\\s+")).toList .groupBy(identity).view.mapValues(_.size).toMap



