Scala – Object-Oriented Meets Functional



Scala – Object-Oriented Meets Functional

0 0


intro-to-scala


On Github corsen2000 / intro-to-scala

Scala

Object-Oriented Meets Functional

  • Who am I
  • Why do I know about scala
  • What is the point of this presentation

Java Virtual Machine

  • Scala compiles to byte code and runs on the JVM
  • Interop between Java and Scala is easy.
  • Groovy, Clojure, jRuby, jython

Scalable

  • Interactive REPL
  • Worksheets
  • Large systems (Twitter, LinkedIn)
  • amazong, foursquare, livingsocial, tumblr, etc...

TypeSafe

  • Commericial support
  • Training
  • Consulting
  • Support for Scala, Akka, Play and associated tools

General Principles

  • Purely object oriented
  • Functional
  • Statically typed
  • Everything is an object
  • Higher order functions

Type Inference

Objects

class Person(val firstName: String, val lastName: String) {
  def fullName(): String = {
      this.firstName + " " + this.lastName
  }
}
  • Benefits of static typing, ease of dynamic typing

Lambdas

val list = List(1, 2, 3, 4 ,5)
val doubles = list.map(x => x * 2)
val ninjaDoubles = list.map(_ * 2)
  • Higher order functions also supported

Pattern Matching

def factorial(n: Int): Int = n match {
	case 0 => 1
	case n => n * factorial(n - 1)
}

Traits

abstract class Entity {
  def fullName(): String
}

class Person(val firstName:String, val lastName:String)
		extends Entity with Ordered[Person] {
	def fullName(): String = {
		this.firstName + " " + this.lastName
	}
	def compare(other: Person): Int = {
		this.fullName().length - other.fullName().length
	}
}

object test {
	val p1 = new Person("Joe", "Bob")         //> p1  : Person = Person@c19af16
	val p2 = new Person("Bob", "Smith")       //> p2  : Person = Person@4ba66ed5
	p1 > p2                                   //> res0: Boolean = false
	p2 > p1                                   //> res1: Boolean = true
}
  • Similar to mixins

Futures

val x = future {
	Thread.sleep(500)
	5
}

val y = future {
	Thread.sleep(750)
	12
}

val z = for (a <- x; b <- y) yield a * b

println("Meanwhile, the main thread goes on!")
                           
Await.result(z, 1 seconds)                      //> res0: Int = 60

Tools

  • Activator
  • Console
  • Scala IDE
  • SBT

Links