Skip to content

Instantly share code, notes, and snippets.

View rdecaire's full-sized avatar

Robert DeCaire rdecaire

  • Inflection Group
  • Toronto
View GitHub Profile
val fruit = List("apple", "apricot", "blueberry", "orange")
// fruit: List[String] = List(apple, apricot, blueberry, orange)
val fruitMap = fruit.groupBy(_.take(1))
// fruitMap: Map(b -> List(blueberry), a -> List(apple, apricot), o -> List(orange))
fruitMap("a")
// List[String] = List(apple, apricot)
def addString(a: String, b: Int): String = a + b
// (a: String, b: Int)String
numbers.foldLeft("")(addString)
// String = 135
def add(a: Int, b: Int): Int = a + b
// (a: Int, b: Int)Int
numbers.fold(0)(add)
// Int = 9
val numbers = List(1, 3, 5)
// numbers: List[Int] = List(1, 3, 5)
numbers.fold(0)(_ + _)
// Int = 9
def fib(a: Int, b: Int): Stream[Int] = a #:: fib(b, a+b)
// (a: Int, b: Int)Stream[Int]
val fibStream = fib(1, 1).take(8)
// fibStream: scala.collection.immutable.Stream[Int] = Stream(1, ?)
fibStream.toList
// List[Int] = List(1, 1, 2, 3, 5, 8, 13, 21)
fibStream
val aSet = Set(1, 3, 3, 5)
// aSet: scala.collection.immutable.Set[Int] = Set(1, 3, 5)
aSet + 4
// scala.collection.immutable.Set[Int] = Set(1, 3, 5, 4)
aSet + 5
// scala.collection.immutable.Set[Int] = Set(1, 3, 5)
val aMap = Map((1 -> "a"), (2 -> "b"))
// aMap: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b)
// Note: the "->" notation is syntactic sugar for defining tuples that makes it
// obvious that you intend that they be used in a Map
aMap.mapValues(_.toUpperCase)
// scala.collection.immutable.Map[Int,String] = Map(1 -> A, 2 -> B)
val o1: Option[String] = Some("hello")
val s1 = o1 match {
case Some(s) => s
case None => "nothing"
}
// s1: String = hello
val o1 = Some("hello")
val o2 = None
val s1 = o1.getOrElse("world")
// s1: String = hello
val s2 = o2.getOrElse("world")
// s2: String = world
val o1 = Some("hello")
val o2 = None
val s1 = o1.getOrElse("world")
// s1: String = hello
val s2 = o2.getOrElse("world")
// s2: String = world