SlideShare a Scribd company logo
railroading into scala
a really fast guide for Java developers
Inspired by Gilt Tech’s Scala Course
scala basics
● Runs on the JVM
● Fully object-oriented, no primitives
● Fully supports functional programming
● Interpreted or compiled to Java bytecode
syntax
● Less verbose than Java
● No semi-colons (except multi-statement
lines)
● Type declaration after identifier:
○ val myVar: Int = 10
● Unit = void
syntax
● Declarations
○ def for functions
○ val for immutables
○ var for mutables
○ lazy val executes at first access, intended for
expensive operations:
lazy val fib = fibonacci(10)
expressions
● Everything is an expression
● No "return" needed, last statement is the
return value
● Anonymous function:
(parameters) => return_type =
{ argument => return_value }
expressions
(Int) => String = { i => "Number " + i }
val x = if (total == 30) {
"Total is 30"
} else {
"Total is something else"
}
loops
● for-loop
for (arg <- args) {
println(arg)
}
for (i <- 0 to 10 by 2) {
println(i)
}
loops
● for-comprehension
val ints = for (arg <- args) yield {
arg.toInt
}
for {
i <- 0 to 2
j <- 1 to 3
} yield {i * j}
functions
● First-class citizens
● Can be returned from a function
● Can be assigned to a val
● Can be nested
● Can have anonymous functions
options
● To get around nulls, Scala gives us Option
● 2 states: Some and None
● Test with .isDefined and .isEmpty
● get() returns the value if Some, else throws
exception
● orElse() and getOrElse() for None
options
Some(“Hello”).isDefined
// res0: Boolean = true
None.getOrElse(“Nothing!”)
// res0: String = Nothing!
exceptions
● No checked exceptions
● Catch matches exceptions by type
exceptions
try{}
catch{
case nfe: NumberFormatException =>
println("Not a number")
case oom: OutOfMemoryException =>
println("Out of memory")
}
finally{}
REPL (Read-Eval-Print-Loop)
● sbt console or sbt console-quick or
scala
● You can import packages as well
● :paste
classes
● Abstract classes and traits
● Only one primary constructor, ancillary
constructors possible: def this(...)
● Members are public by default
● Nothing vs. Null types
● def can be overridden by val
classes
trait Shape {
def area: Double
}
class Circle(val radius: Double) extends Shape {
override val area = math.Pi * radius
val circumference = 2 * math.Pi * radius
}
val c = new Circle(1)
c.radius // res0: Double = 1.0
c.area // res1: Double = 3.141592653589793
c.circumference // res2: Double = 6.283185307179586
classes
class ModifiableRectangle(var x: Double, var y: Double)
extends Shape {
def this(x: Double) = this(x, x)
override def area = x * y
}
class ModifiableSquare(a: Double) extends
ModifiableRectangle(a, a) {
private val originalArea = a * a
}
traits
● Similar to interfaces, but can have default
implementation
● No constructor
● Multiple inheritance: initialize left to right,
linearize right to left
traits
trait IntStack {
def pop(): Option[Int]
def push(x: Int): Unit
def isEmpty: Boolean
}
class BasicStack extends IntStack {
private val stack = new collection.mutable.Stack[Int]()
override def pop(): Option[Int] = {
if (stack.empty()) { None }
else { Some(stack.pop()) }
}
override def push(x: Int): Unit = stack.push(x)
override def isEmpty = stack.empty
}
traits
trait Doubling extends IntStack {
abstract override def push(x: Int): Unit = super.push(x * 2)
}
trait Incrementing extends IntStack {
abstract override def push(x: int): Unit = super.push(x + 1)
}
class MyStack extends BasicStack with Doubling with Incrementing
class YourStack extends BasicStack with Incrementing with Doubling
val me = new MyStack()
me.push(2)
me.pop
// res0: Option[Int] = Some(6)
val you = new YourStack()
you.push(2)
you.pop
// res0: Option[Int] = Some(5)
objects
● Equivalent to static class
● May extend/implement a class or trait
(singleton)
companion object
● Same name as companion class, same file
● Equivalent to static methods
● May apply() methods
companion object
class MyStack extends BasicStack
object MyStack {
def apply(): MyStack = new MyStack()
def apply(ints: Int*): MyStack = {
val stack = new MyStack()
ints.foreach(stack.push(_))
stack
}
}
val myStack = new MyStack()
val yourStack = MyStack()
val ourStack = MyStack(1, 2, 3, 4)
enumerations
● Extend scala.Enumeration
● Values have inner type Enumeration.Value
object Color extends Enumeration {
val Red, Green, Blue = Value
}
val red = Color.Red
Java Scala
Interface Trait
Abstract Class Trait or Abstract Class
Class Class
Object/Instance Object/Instance
Static Class, Singleton Object
Static Members Companion Object
Enum Enumeration
case classes
● Implements hashCode, equals, and
toString methods
● Add companion object with apply()
● Implements copy()
● Great for pattern matching!
immutability
● val vs. var
● Reduce side effects
● Concurrency issues
● Transform data vs. update data
collections
● Immutable vs. mutable collections
lists
● Construction: List(1, 2, 3), List.empty
[String], List[String] = Nil
● Access: myList(2)
● Concatenation: myList ::: otherList, 0 ::
myList, myList :+ 4
● Update: myList.updated(1, 9)
● isEmpty
● head, tail, init, last
● headOption, lastOption
● take, drop, slice
● toString, mkString
● contains, exists, forall (return Boolean)
● find (returns Option)
lists
sets and maps
● Construction: Set(1, 2, 3)
● Combination:
○ mySet ++ Set(5, 6, 7)
○ myMap ++ Map("three" -> 3)
● Insert:
○ mySet + 9
○ myMap + ("three" -> 3)
● Access: myMap.get("one")
monads
map
def map[B](f: A => B): List[B]
flatMap
def flatMap[B](f: A => List[B]): List[B]
filter
def filter(f: A => Boolean): List[A]
higher order functions
foldLeft
def foldLeft[B](z: B)(op: (B, A) = B): B
List(1, 2, 3, 4).foldLeft(0)({ (a: Int, b: Int) => a + b
})
collect
(1 until 100).toList.collect {
case i if (i % 2 == 0) => "even"
case _ => "odd"
}
higher order functions
groupBy
List("one", "two", "three", "four", "five").
groupBy(a => a.size)
partition
(1 until 10).toList.partition(_ % 2 == 0)
learn more
Scala Docs
http://www.scala-lang.org/documentation/
Twitter’s Scala School
https://twitter.github.io/scala_school/
Coursera
https://www.coursera.org/course/progfun
https://www.coursera.org/course/reactive
Books
Scala for the Impatient
Ninety-Nine Scala Problems
http://aperiodic.net/phil/scala/s-99/

More Related Content

What's hot (20)

PDF
Web futures
Brendan Eich
 
PDF
JS Responsibilities
Brendan Eich
 
PDF
Refinement Types for Haskell
Martin Ockajak
 
PDF
Introduction to idris
Conor Farrell
 
PDF
Comparing Haskell & Scala
Martin Ockajak
 
PDF
Fluent14
Brendan Eich
 
KEY
Deriving Scalaz
nkpart
 
PDF
Scala for Java Developers
Martin Ockajak
 
PDF
Scala taxonomy
Radim Pavlicek
 
PDF
ScalaTrainings
Chinedu Ekwunife
 
PDF
Int64
Brendan Eich
 
PDF
Scala Bootcamp 1
Knoldus Inc.
 
PPTX
Constructors and Destructors
Keyur Vadodariya
 
PPTX
Java8: what's new and what's hot
Sergii Maliarov
 
PDF
Constructors and Destructors
Dr Sukhpal Singh Gill
 
PDF
JavaScript objects and functions
Victor Verhaagen
 
PPTX
Constructor and destructor
Shubham Vishwambhar
 
PDF
Scala categorytheory
Knoldus Inc.
 
PDF
Mining Functional Patterns
Debasish Ghosh
 
PDF
Codemotion akka persistence, cqrs%2 fes y otras siglas del montón
Javier Santos Paniego
 
Web futures
Brendan Eich
 
JS Responsibilities
Brendan Eich
 
Refinement Types for Haskell
Martin Ockajak
 
Introduction to idris
Conor Farrell
 
Comparing Haskell & Scala
Martin Ockajak
 
Fluent14
Brendan Eich
 
Deriving Scalaz
nkpart
 
Scala for Java Developers
Martin Ockajak
 
Scala taxonomy
Radim Pavlicek
 
ScalaTrainings
Chinedu Ekwunife
 
Scala Bootcamp 1
Knoldus Inc.
 
Constructors and Destructors
Keyur Vadodariya
 
Java8: what's new and what's hot
Sergii Maliarov
 
Constructors and Destructors
Dr Sukhpal Singh Gill
 
JavaScript objects and functions
Victor Verhaagen
 
Constructor and destructor
Shubham Vishwambhar
 
Scala categorytheory
Knoldus Inc.
 
Mining Functional Patterns
Debasish Ghosh
 
Codemotion akka persistence, cqrs%2 fes y otras siglas del montón
Javier Santos Paniego
 

Viewers also liked (9)

PPTX
Mallory
merichards
 
PDF
03 club in.udine.aggiornamenti
Stefano Tazzi
 
PDF
01 a club-aspiranti - monzabrianzain
Stefano Tazzi
 
PDF
07 c urban-creativityassembleaclubin
Stefano Tazzi
 
DOCX
Base de camisa t
pamori019
 
PDF
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
Stefano Tazzi
 
PDF
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
Stefano Tazzi
 
PDF
02 ivana pais-confrontomilanin-toscanain
Stefano Tazzi
 
PDF
01 club in.stefanotazzi
Stefano Tazzi
 
Mallory
merichards
 
03 club in.udine.aggiornamenti
Stefano Tazzi
 
01 a club-aspiranti - monzabrianzain
Stefano Tazzi
 
07 c urban-creativityassembleaclubin
Stefano Tazzi
 
Base de camisa t
pamori019
 
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
Stefano Tazzi
 
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
Stefano Tazzi
 
02 ivana pais-confrontomilanin-toscanain
Stefano Tazzi
 
01 club in.stefanotazzi
Stefano Tazzi
 
Ad

Similar to Railroading into Scala (20)

PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Scala - core features
Łukasz Wójcik
 
ODP
Scala ntnu
Alf Kristian Støyle
 
PDF
Programming in scala - 1
Mukesh Kumar
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
PPTX
Scala fundamentals
Alfonso Ruzafa
 
PDF
Lecture 5: Functional Programming
Eelco Visser
 
PPTX
Qcon2011 functions rockpresentation_scala
Michael Stal
 
PDF
The Scala Programming Language
league
 
PDF
Python to scala
kao kuo-tung
 
PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
PPT
An introduction to scala
Mohsen Zainalpour
 
PDF
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
PDF
Scala for Java Programmers
Eric Pederson
 
PPTX
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
PDF
Scala Paradigms
Tom Flaherty
 
PDF
Introduction to Asynchronous scala
Stratio
 
PDF
Short intro to scala and the play framework
Felipe
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala - core features
Łukasz Wójcik
 
Programming in scala - 1
Mukesh Kumar
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Scala fundamentals
Alfonso Ruzafa
 
Lecture 5: Functional Programming
Eelco Visser
 
Qcon2011 functions rockpresentation_scala
Michael Stal
 
The Scala Programming Language
league
 
Python to scala
kao kuo-tung
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
An introduction to scala
Mohsen Zainalpour
 
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Scala for Java Programmers
Eric Pederson
 
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
Scala Paradigms
Tom Flaherty
 
Introduction to Asynchronous scala
Stratio
 
Short intro to scala and the play framework
Felipe
 
Ad

Recently uploaded (20)

PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
July Patch Tuesday
Ivanti
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
July Patch Tuesday
Ivanti
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 

Railroading into Scala

  • 1. railroading into scala a really fast guide for Java developers Inspired by Gilt Tech’s Scala Course
  • 2. scala basics ● Runs on the JVM ● Fully object-oriented, no primitives ● Fully supports functional programming ● Interpreted or compiled to Java bytecode
  • 3. syntax ● Less verbose than Java ● No semi-colons (except multi-statement lines) ● Type declaration after identifier: ○ val myVar: Int = 10 ● Unit = void
  • 4. syntax ● Declarations ○ def for functions ○ val for immutables ○ var for mutables ○ lazy val executes at first access, intended for expensive operations: lazy val fib = fibonacci(10)
  • 5. expressions ● Everything is an expression ● No "return" needed, last statement is the return value ● Anonymous function: (parameters) => return_type = { argument => return_value }
  • 6. expressions (Int) => String = { i => "Number " + i } val x = if (total == 30) { "Total is 30" } else { "Total is something else" }
  • 7. loops ● for-loop for (arg <- args) { println(arg) } for (i <- 0 to 10 by 2) { println(i) }
  • 8. loops ● for-comprehension val ints = for (arg <- args) yield { arg.toInt } for { i <- 0 to 2 j <- 1 to 3 } yield {i * j}
  • 9. functions ● First-class citizens ● Can be returned from a function ● Can be assigned to a val ● Can be nested ● Can have anonymous functions
  • 10. options ● To get around nulls, Scala gives us Option ● 2 states: Some and None ● Test with .isDefined and .isEmpty ● get() returns the value if Some, else throws exception ● orElse() and getOrElse() for None
  • 11. options Some(“Hello”).isDefined // res0: Boolean = true None.getOrElse(“Nothing!”) // res0: String = Nothing!
  • 12. exceptions ● No checked exceptions ● Catch matches exceptions by type
  • 13. exceptions try{} catch{ case nfe: NumberFormatException => println("Not a number") case oom: OutOfMemoryException => println("Out of memory") } finally{}
  • 14. REPL (Read-Eval-Print-Loop) ● sbt console or sbt console-quick or scala ● You can import packages as well ● :paste
  • 15. classes ● Abstract classes and traits ● Only one primary constructor, ancillary constructors possible: def this(...) ● Members are public by default ● Nothing vs. Null types ● def can be overridden by val
  • 16. classes trait Shape { def area: Double } class Circle(val radius: Double) extends Shape { override val area = math.Pi * radius val circumference = 2 * math.Pi * radius } val c = new Circle(1) c.radius // res0: Double = 1.0 c.area // res1: Double = 3.141592653589793 c.circumference // res2: Double = 6.283185307179586
  • 17. classes class ModifiableRectangle(var x: Double, var y: Double) extends Shape { def this(x: Double) = this(x, x) override def area = x * y } class ModifiableSquare(a: Double) extends ModifiableRectangle(a, a) { private val originalArea = a * a }
  • 18. traits ● Similar to interfaces, but can have default implementation ● No constructor ● Multiple inheritance: initialize left to right, linearize right to left
  • 19. traits trait IntStack { def pop(): Option[Int] def push(x: Int): Unit def isEmpty: Boolean } class BasicStack extends IntStack { private val stack = new collection.mutable.Stack[Int]() override def pop(): Option[Int] = { if (stack.empty()) { None } else { Some(stack.pop()) } } override def push(x: Int): Unit = stack.push(x) override def isEmpty = stack.empty }
  • 20. traits trait Doubling extends IntStack { abstract override def push(x: Int): Unit = super.push(x * 2) } trait Incrementing extends IntStack { abstract override def push(x: int): Unit = super.push(x + 1) } class MyStack extends BasicStack with Doubling with Incrementing class YourStack extends BasicStack with Incrementing with Doubling val me = new MyStack() me.push(2) me.pop // res0: Option[Int] = Some(6) val you = new YourStack() you.push(2) you.pop // res0: Option[Int] = Some(5)
  • 21. objects ● Equivalent to static class ● May extend/implement a class or trait (singleton)
  • 22. companion object ● Same name as companion class, same file ● Equivalent to static methods ● May apply() methods
  • 23. companion object class MyStack extends BasicStack object MyStack { def apply(): MyStack = new MyStack() def apply(ints: Int*): MyStack = { val stack = new MyStack() ints.foreach(stack.push(_)) stack } } val myStack = new MyStack() val yourStack = MyStack() val ourStack = MyStack(1, 2, 3, 4)
  • 24. enumerations ● Extend scala.Enumeration ● Values have inner type Enumeration.Value object Color extends Enumeration { val Red, Green, Blue = Value } val red = Color.Red
  • 25. Java Scala Interface Trait Abstract Class Trait or Abstract Class Class Class Object/Instance Object/Instance Static Class, Singleton Object Static Members Companion Object Enum Enumeration
  • 26. case classes ● Implements hashCode, equals, and toString methods ● Add companion object with apply() ● Implements copy() ● Great for pattern matching!
  • 27. immutability ● val vs. var ● Reduce side effects ● Concurrency issues ● Transform data vs. update data
  • 28. collections ● Immutable vs. mutable collections
  • 29. lists ● Construction: List(1, 2, 3), List.empty [String], List[String] = Nil ● Access: myList(2) ● Concatenation: myList ::: otherList, 0 :: myList, myList :+ 4 ● Update: myList.updated(1, 9) ● isEmpty
  • 30. ● head, tail, init, last ● headOption, lastOption ● take, drop, slice ● toString, mkString ● contains, exists, forall (return Boolean) ● find (returns Option) lists
  • 31. sets and maps ● Construction: Set(1, 2, 3) ● Combination: ○ mySet ++ Set(5, 6, 7) ○ myMap ++ Map("three" -> 3) ● Insert: ○ mySet + 9 ○ myMap + ("three" -> 3) ● Access: myMap.get("one")
  • 32. monads map def map[B](f: A => B): List[B] flatMap def flatMap[B](f: A => List[B]): List[B] filter def filter(f: A => Boolean): List[A]
  • 33. higher order functions foldLeft def foldLeft[B](z: B)(op: (B, A) = B): B List(1, 2, 3, 4).foldLeft(0)({ (a: Int, b: Int) => a + b }) collect (1 until 100).toList.collect { case i if (i % 2 == 0) => "even" case _ => "odd" }
  • 34. higher order functions groupBy List("one", "two", "three", "four", "five"). groupBy(a => a.size) partition (1 until 10).toList.partition(_ % 2 == 0)
  • 35. learn more Scala Docs http://www.scala-lang.org/documentation/ Twitter’s Scala School https://twitter.github.io/scala_school/ Coursera https://www.coursera.org/course/progfun https://www.coursera.org/course/reactive Books Scala for the Impatient Ninety-Nine Scala Problems http://aperiodic.net/phil/scala/s-99/