Skip to content

Instantly share code, notes, and snippets.

@nburoojy
Created July 6, 2016 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nburoojy/739522acc8f021e56e711a0905bece51 to your computer and use it in GitHub Desktop.
Save nburoojy/739522acc8f021e56e711a0905bece51 to your computer and use it in GitHub Desktop.
Scala tour
// assignment
val a: String = "hello"
a
> "hello"
// type safety
val a: Int = "hello"
> error
// Type inference
val b = "hello"
// val vs var
b = "goodbye"
> error
var c = "hello"
c = goodbye
// Functions
def square(n: Int): Int = n * n
val cube = (x: Int) => x * x * x
// Collection
// cons
val l = List(1, 2, 3)
val l2 = 1 :: 2 :: 3 :: Nil
val l3 = 5 :: l
l.head
l.tail
// No need for "for loops"
l.map(cube)
l.map(a => 2 * a)
l.map(2 * _)
l map(2 * _)
// Options (No need for null)
scala> val x: Option[String] = Some("foo")
x: Option[String] = Some(foo)
scala> val y: Option[String] = None
y: Option[String] = None
scala> x.map(s => "Prefix" + s)
res16: Option[String] = Some(Prefixfoo)
scala> y.map(s => "Prefix" + s)
res17: Option[String] = None
scala> x.getOrElse("nothing there!")
res18: String = foo
scala> y.getOrElse("nothing there!")
res19: String = nothing there!
// flatten
scala> val l = List(Some(1), None, Some(4), None, Some(5))
l: List[Option[Int]] = List(Some(1), None, Some(4), None, Some(5))
scala> l.flatten
res20: List[Int] = List(1, 4, 5)
scala> val l = List(1, 2, 3, 4)
l: List[Int] = List(1, 2, 3, 4)
scala> l.flatMap(a => if (a % 2 == 0) Some(a) else None)
res21: List[Int] = List(2, 4)
// Pattern Matching
scala> val a = 7
a: Int = 7
scala> a match {
| case 0 => "Zero"
| case 7 => "Seven"
| case _ => "Other"
| }
res22: String = Seven
scala> case class Student(name: String, age: Int, address: Option[String])
defined class Student
scala> val fred = Student("Fred", 31, Some("123 main st"))
fred: Student = Student(Fred,31,Some(123 main st))
scala> fred match {
| case Student(_, _, Some(addr)) => addr
| case _ => "homeless"
| }
res24: String = 123 main st
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment