Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Scala Cheat Sheet

Basics

// values, strings, printing
val x = 5; var y = 10; val s = s"x = $x"; println(f"$pi%.2f")
"42".toInt; "4x".toIntOption; 42.toString; 7 / 2; 7 / 2.0
@main def run(): Unit = println("hi")

Control flow

val r = if a > b then a else b
x match { case 1 => "one"; case n if n > 1 => "many"; case _ => "other" }
for i <- 1 to 10 if i % 2 == 0 do println(i)
val sq = for i <- 1 to 5 yield i * i
while cond do step()

Collections

val l = List(1, 2, 3); 0 :: l; l :+ 4; l ++ List(5); l.head; l.tail
l.map(_ * 2); l.filter(_ > 1); l.foldLeft(0)(_ + _); l.sum; l.sorted; l.reverse
l.groupBy(_ % 2); l.zipWithIndex; l.distinct; l.take(2); l.find(_ > 1)
val m = Map("a" -> 1); m + ("b" -> 2); m.getOrElse("z", 0); m.keys; m.values

Classes and traits

case class User(name: String, age: Int)
class A(val x: Int) extends B with T { override def toString = s"A($x)" }
trait T { def f: Int; def g: Int = f * 2 }
object Utils { def helper(): Unit = () }
enum Color { case Red, Green }

Functional and errors

val f = (x: Int) => x + 1; def g(h: Int => Int) = h(1)
Option(x).map(_ + 1).getOrElse(0)
Try(risky()).toOption; Right(1).map(_ + 1); Left("err")
extension (s: String) def twice: String = s * 2

Full Scala documentation