Scala

 

About the speaker

  • Software Engineer for GE Healthcare
  • Mostly Java, currently full stack (Java, AngularJS)
  • Reactive programming of any kind (AKKA, Rxjava, Redux)
  • Open Source Advocate
  • I also play Magic: the gathering

DISCLAIMER

I am still learning :(

 

I will answer your question in a eventual consistency style.
 

What is Scala

  • Scala is both functional and object oriented
  • JVM
  • Acronym for "Scalable Language"
  • Founded by Martin Odersky
  • Supported by Lightbend (used to be TypeSafe Inc)

Scala

"I can honestly say...
if someone shad shown me
the proramming Scala book back in 2003,
I'd probably have never created Groovy"

                            - James Strachan, Groovy creator

Scala

https://www.lightbend.com/blog/how-scala-compares-20-programming-languages-reddit-analysis

Why Scala?

  • Statically Type
  • Higher Order Functions(Functions
  • as value Types)
  • "expressive" and "concise"
  • Almost all Java libraries can be used by Scala
  • Easier to write multi-threaded applications
  • Partial Functions
  • Pattern Matching
  • And more....

Why Scala

 

  • "expressive" and "concise"
    • no ;
    • everything returns
    • if only one statement, no need to add { }
      // even for function!

Basics

Variable Assignments and Declarations

scala> var stockPrice = 20.00
stockPrice: Double = 20.0

scala> var stockPrice = 40.00
stockPrice: Double = 40.0


scala> val numOfShares = 32
numOfShares: Int = 32

scala> numOfShares = 122
<console>:8: error: reassignment to val
       numOfShares = 122
                   ^

scala> val distance = { val dx = x - x0; val dy = y - y0; 
                         sqrt(dx * dx + dy * dy) 
                       }

scala> val person = new Person("Kyel",21)

val -  (Read-only)

 

 var -  (Read-Write)

Variable Assignments and Declarations

//Specifying type information

scala> val person:Person = new Person("Kyel",21)

scala> val listItems: List[Int] = List(1,2,3,4,5)

Loops

/**Range Generates a 
/*sequence of Inclusive/exclusive 
/*sequence <start> to/until <end> <by increment>
**/

scala> 0 to 10
res7: scala.collection.immutable.Range.Inclusive
 = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> 0 to 10 by 2
res11: scala.collection.immutable.Range 
= Range(0, 2, 4, 6, 8, 10)

scala> 0 until 10 by 2
res12: scala.collection.immutable.Range 
= Range(0, 2, 4, 6, 8)


For comprehension

for(i <- 1 to 10){
   println(i)
}

for{
   i <- 1 to 10
}{
    println(i)
}

//Iterator Guard
for(i <- 1 to 10; if i % 2== 0; x2 = i * 2)
    println(i)
//Value binding
for(i <- 1 to 10; x2 = i * 2; if i % 2 == 0 ) 
        println(x2)

"For yield"

for{
 i <- 1 to 10
}yield{
  i
}

res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Function Definitions

scala> def abs(n: Int): Int = { 
           if(n < 0) -n else n  
        }
abs: (n: Int)Int

scala> def abs(n: Int): Int = if(n < 0) -n else n
abs: (n: Int)Int

scala> def abs(n: Int) =  if(n < 0) -n else n
abs: (n: Int)Int

//"Generic" Function. 
//Type information
scala> def someOperation[A](x: A) = { x }
someOperation: [A](x: A)A

//Another Syntactic sugar for Scala  when writing 
//a function that has no arguments
scala> def noParameterFunction = { println("A function of no parameter") }
noParameterFunction: Unit

HOF - Functions

def factorial(f: String => Unit) = {
  f("Hello, World!")
}

def operation(f: (Int,Int) => Int,x:Int, y:Int ): Int = { f(x,y) }

//An example of function composition
def func[A,B,C](f1: A => B, f2: B=>C): A => C  = {
    (a:A) =>  f2(f1(a))
  }
  

The _ operator


// scala
List(1,2,3,4,5).foreach(print(_))

// java
List(1,2,3,4,5).foreach( a => print(a))

Case Classes

  • Think of them as value objects or DTOs
  • All fields are immutable
  • No more boilerplate code(hashCode and equals has been generated)
  • Can be used for Pattern Matching
  • Maximum of 22 fields only
  • Compared by fields instead by ref

Pattern Matching

  • Case keyword on steroids
  • Algebraic data types
  •  "pattern matching is a way of assigning names to things (or binding those names to those things), and possibly breaking down expressions into subexpressions at the same time" 
  • Allows you to "Pattern" match 
    -Strings
    -Numbers
    -Regular Expressions
    -Case classes

Pattern Matching

scala> val message = "hello" 
message: String = "hello"

scala> val person1 = Person("Rich",21)
person1: Person = Person(Rich,21)

def identifyType(item: Any)  = item match{
          case s:String => "Is a String"
          case i:Int => "Is an Int"
          case d:Double => "Is a Double"
          case _ => "Type Not Supported"
      }


scala> identifyType(message)
res6: String = Is a String

scala> identifyType(person1)
res8: String = Type Not Supported

Pattern Matching

abstract class Expr
case class Number(n: Int) extends Expr
case class Sum(e1: Expr, e2: Expr) extends Expr

def eval(e: Expr): Int = e match {
  case Number(x) => x
  case Sum(l, r) => eval(l) + eval(r)
}
def eval(e: Expr): Int = {
  <synthetic> val temp10: Expr = e;
  if (temp10.$isInstanceOf[Number]())
    temp10.$asInstanceOf[Number]().n()
  else
    if (temp10.$isInstanceOf[Sum]())
      {
        <synthetic> val temp13: Sum = 
            temp10.$asInstanceOf[Sum]();
        
        Main.this.eval(temp13.e1()).+(Main.this.eval(temp13.e2()))
      }
    else
      throw new MatchError(temp10)
};

Pattern Matching: qsort (more..)




def qsort(list: List[Int]): List[Int] = list match {
  case Nil => Nil
  case pivot :: tail =>
    val (smaller, rest) = tail.partition(_ < pivot)
    qsort(smaller) ::: pivot :: qsort(rest)
}

Java: quicksort


public static void quickSort(int[] arr, int low, int high) {
		if (arr == null || arr.length == 0) return;
		if (low >= high) return;
 
		// pick the pivot
		int middle = low + (high - low) / 2;
		int pivot = arr[middle];
 
		// make left < pivot and right > pivot
		int i = low, j = high;
		while (i <= j) {
			while (arr[i] < pivot) { i++;}
 
			while (arr[j] > pivot) {j--;}
 
			if (i <= j) {
				int temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
				i++;
				j--;
			}
		}
 
		// recursively sort two sub parts
		if (low < j) quickSort(arr, low, j);
		if (high > i) quickSort(arr, i, high);
	}

Pattern Matching 

expr match {
  case List(1,_,_) => " a list with three element and the first element is 1"
  case List(_*)  => " a list with zero or more elements "
  case Map[_,_] => " matches a map with any key type and any value type "
  case _ =>
  }

Reduce / Fold


List(4, 5, 6).fold(0)(_*10 + _)  == ?
456

List(4, 5, 6).foldLeft(0)(_*10 + _)  == ?
456

List(4, 5, 6).foldRight(0)(_*10 + _) == ?
150

List(4, 5, 6).reduce(_*10 + _) == ?


List(4, 5, 6).reduceLeft(_*10 + _) == ?

 
List(4, 5, 6).reduceRight(_*10 + _) == ?

Tuple




val t = (4,3,2,1)

val sum = t._1 + t._2 + t._3 + t._4


val stuff = (42, "fish")


stuff.getClass
res0: java.lang.Class[_ <: (Int, java.lang.String)] = class scala.Tuple2

Scala stack

SBT

Play

Akka

ScalaTest

 

Lesser known Scala 

SCALAJS ->www.scala-js.org/

Ammoite -> Lihaoyi.com/ammonite

 

scastie -> in beta

ScalaFx -> github

Learning

Fin

Everything I know about Scala!

By Richard Hsu

Everything I know about Scala!

My Scala Journey

  • 1,186