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

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

What's hot (20)

Web futures
Web futuresWeb futures
Web futures
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idris
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Fluent14
Fluent14Fluent14
Fluent14
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
Int64
Int64Int64
Int64
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functions
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Mining Functional Patterns
Mining Functional PatternsMining Functional Patterns
Mining Functional Patterns
 
Codemotion akka persistence, cqrs%2 fes y otras siglas del montón
Codemotion   akka persistence, cqrs%2 fes y otras siglas del montónCodemotion   akka persistence, cqrs%2 fes y otras siglas del montón
Codemotion akka persistence, cqrs%2 fes y otras siglas del montón
 

Viewers also liked

Mallory
MalloryMallory
Mallory
merichards
 
03 club in.udine.aggiornamenti
03 club in.udine.aggiornamenti03 club in.udine.aggiornamenti
03 club in.udine.aggiornamenti
Stefano Tazzi
 
01 a club-aspiranti - monzabrianzain
01 a   club-aspiranti - monzabrianzain01 a   club-aspiranti - monzabrianzain
01 a club-aspiranti - monzabrianzain
Stefano Tazzi
 
07 c urban-creativityassembleaclubin
07 c   urban-creativityassembleaclubin07 c   urban-creativityassembleaclubin
07 c urban-creativityassembleaclubin
Stefano Tazzi
 
Base de camisa t
Base de camisa tBase de camisa t
Base de camisa t
pamori019
 
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
Stefano Tazzi
 
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
Stefano Tazzi
 
02 ivana pais-confrontomilanin-toscanain
02 ivana pais-confrontomilanin-toscanain02 ivana pais-confrontomilanin-toscanain
02 ivana pais-confrontomilanin-toscanain
Stefano Tazzi
 
01 club in.stefanotazzi
01 club in.stefanotazzi01 club in.stefanotazzi
01 club in.stefanotazziStefano Tazzi
 

Viewers also liked (9)

Mallory
MalloryMallory
Mallory
 
03 club in.udine.aggiornamenti
03 club in.udine.aggiornamenti03 club in.udine.aggiornamenti
03 club in.udine.aggiornamenti
 
01 a club-aspiranti - monzabrianzain
01 a   club-aspiranti - monzabrianzain01 a   club-aspiranti - monzabrianzain
01 a club-aspiranti - monzabrianzain
 
07 c urban-creativityassembleaclubin
07 c   urban-creativityassembleaclubin07 c   urban-creativityassembleaclubin
07 c urban-creativityassembleaclubin
 
Base de camisa t
Base de camisa tBase de camisa t
Base de camisa t
 
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
03 ClubIN Montefiore Dell' Aso - Comunicazione - Stefano Mastella, Eugenio Leone
 
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
02 ClubIN Montefiore Dell'Aso - Modello pesi e misure - Stefano Mastella
 
02 ivana pais-confrontomilanin-toscanain
02 ivana pais-confrontomilanin-toscanain02 ivana pais-confrontomilanin-toscanain
02 ivana pais-confrontomilanin-toscanain
 
01 club in.stefanotazzi
01 club in.stefanotazzi01 club in.stefanotazzi
01 club in.stefanotazzi
 

Similar to Railroading into Scala

An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
Scala ntnu
Scala ntnuScala ntnu
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Python to scala
Python to scalaPython to scala
Python to scala
kao kuo-tung
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Mohsen Zainalpour
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
Stratio
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
Felipe
 

Similar to Railroading into Scala (20)

An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 

Recently uploaded

dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
saastr
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 

Recently uploaded (20)

dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 

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/