SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
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/

Weitere ähnliche Inhalte

Was ist angesagt?

JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS ResponsibilitiesBrendan Eich
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for HaskellMartin Ockajak
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idrisConor Farrell
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java DevelopersMartin Ockajak
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur 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 hotSergii Maliarov
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functionsVictor Verhaagen
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Mining Functional Patterns
Mining Functional PatternsMining Functional Patterns
Mining Functional PatternsDebasish 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ónJavier Santos Paniego
 

Was ist angesagt? (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
 

Andere mochten auch

03 club in.udine.aggiornamenti
03 club in.udine.aggiornamenti03 club in.udine.aggiornamenti
03 club in.udine.aggiornamentiStefano Tazzi
 
01 a club-aspiranti - monzabrianzain
01 a   club-aspiranti - monzabrianzain01 a   club-aspiranti - monzabrianzain
01 a club-aspiranti - monzabrianzainStefano Tazzi
 
07 c urban-creativityassembleaclubin
07 c   urban-creativityassembleaclubin07 c   urban-creativityassembleaclubin
07 c urban-creativityassembleaclubinStefano Tazzi
 
Base de camisa t
Base de camisa tBase de camisa t
Base de camisa tpamori019
 
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 LeoneStefano 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 MastellaStefano Tazzi
 
02 ivana pais-confrontomilanin-toscanain
02 ivana pais-confrontomilanin-toscanain02 ivana pais-confrontomilanin-toscanain
02 ivana pais-confrontomilanin-toscanainStefano Tazzi
 
01 club in.stefanotazzi
01 club in.stefanotazzi01 club in.stefanotazzi
01 club in.stefanotazziStefano Tazzi
 

Andere mochten auch (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
 

Ähnlich wie Railroading into Scala

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 DevelopersMiles Sabin
 
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 DevelopersMiles Sabin
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
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 DevelopersMiles Sabin
 
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 DevelopersSkills Matter
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
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 frameworkFelipe
 

Ähnlich wie Railroading into Scala (20)

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
 
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
 
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
 
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 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
 
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
 

Kürzlich hochgeladen

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Kürzlich hochgeladen (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

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/