SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Scala 101
Beyond Java: JVM FP, July 2014
Shai Yallin, Wix.com
audience.filter(_.usesJava).foreach { member =>
sayHi(member)
}
A short overview of Scala’s features
• A functional/OO programming language that runs on the JVM
• Everything is an object – no primitive types
• Functions are first-class members, every function is a value,
including what is usually an operator*
• Scala is statically-typed and supports type inference
* Some of these are synthetic functions
A short overview of Scala’s features
• Lambda expressions, closures and currying naturally
• Pattern matching
• Multiple inheritance through Traits
• Comprehensive collections library
Determinism via Immutability
Scala encourages everything to be immutable by default:
• Variables (vals)
• Collections
• Value objects (using Case Classes)
Better type safety
• Scala is statically and strongly typed; type inference keeps the
code lean and mean
• Stricter generics (in comparison to Java) provide better compile-
time checks
• Advanced features include structural types and type aliases
Case Classes
Good software engineering makes use of value objects. These need to
encapsulate the way they represent their state, to provide information hiding
and to be easy to maintain.
case class Person(
firstName: String,
lastName: String,
age: Int)
val authorOfPascal = Person("Niklaus", "Wirth", 80)
Case classes give us:
Factory methods Person("Niklaus", "Wirth", 80)
Hashcode authorOfPascal.hashCode == 1423465897
Equals authorOfPascal.equals(authorOfModula) == true
Copy val happyBirthday =
authorOfPascal.copy(age = 81)
Pattern matching Wait for it :-)
Collections
Some collection types:
• Seq (abstract ordered sequence)
• List (linked list)
• Set (yeah, it’s a set)
• Map (dictionary/hash)
A collection can be:
• Immutable / Mutable
• Synchronous / Parallel
Collections
With type inference, trivial to instantiate
val numbers = List(1, 2, 3)
val numbers2 = 1 :: 2 :: 3 :: Nil
val firstNames = Set("john", "mary", "muhammad”)
val caloriesPer100gr = Map(
"bacon" -> 541,
"fries" -> 312,
"lettuce" -> 15 )
Collection functions++ ++: +: /: /:
:+ :: ::: : addString
aggregate andThen apply applyOrElse asInstanceOf
canEqual collect collectFirst combinations companion
compose contains containsSlice copyToArray copyToBuffer
corresponds count diff distinct drop
dropRight dropWhile endsWith exists filter
filterNot find flatMap flatten fold
foldLeft foldRight forall foreach genericBuilder
groupBy grouped hasDefiniteSize head headOption
indexOf indexOfSlice indexWhere indices init
inits intersect isDefinedAt isEmpty isInstanceOf
isTraversableAgain iterator last lastIndexOf lastIndexOfSlice
lastIndexWhere lastOption length lengthCompare lift
map mapConserve max maxBy min
minBy mkString nonEmpty orElse padTo
par partition patch permutations prefixLength
product productArity productElement productIterator productPrefix
reduce reduceLeft reduceLeftOption reduceOption reduceRight
reduceRightOption repr reverse reverseIterator reverseMap
reverse_::: runWith sameElements scan scanLeft
scanRight segmentLength seq size slice
sliding sortBy sortWith sorted span
splitAt startsWith stringPrefix sum tail
tails take takeRight takeWhile to
toArray toBuffer toIndexedSeq toIterable toIterator
toList toMap toSeq toSet toStream
toString toTraversable toVector transpose union
unzip unzip3 updated view withFilter
Collection functions++ ++: +: /: /:
:+ :: ::: : addString
aggregate andThen apply applyOrElse asInstanceOf
canEqual collect collectFirst combinations companion
compose contains containsSlice copyToArray copyToBuffer
corresponds count diff distinct drop
dropRight dropWhile endsWith exists filter
filterNot find flatMap flatten fold
foldLeft foldRight forall foreach genericBuilder
groupBy grouped hasDefiniteSize head headOption
indexOf indexOfSlice indexWhere indices init
inits intersect isDefinedAt isEmpty isInstanceOf
isTraversableAgain iterator last lastIndexOf lastIndexOfSlice
lastIndexWhere lastOption length lengthCompare lift
map mapConserve max maxBy min
minBy mkString nonEmpty orElse padTo
par partition patch permutations prefixLength
product productArity productElement productIterator productPrefix
reduce reduceLeft reduceLeftOption reduceOption reduceRight
reduceRightOption repr reverse reverseIterator reverseMap
reverse_::: runWith sameElements scan scanLeft
scanRight segmentLength seq size slice
sliding sortBy sortWith sorted span
splitAt startsWith stringPrefix sum tail
tails take takeRight takeWhile to
toArray toBuffer toIndexedSeq toIterable toIterator
toList toMap toSeq toSet toStream
toString toTraversable toVector transpose union
unzip unzip3 updated view withFilter
Pattern matching
abstract class Gender
case object Male extends Gender
case object Female extends Gender
abstract class MaritalStatus
case object Single extends MaritalStatus
case object Married extends MaritalStatus
case object Divorced extends MaritalStatus
case object Widowed extends MaritalStatus
case class Person(
firstName: String, lastName: String, age: Int,
gender: Option[ Gender ], maritalStatus: Option[ MaritalStatus ])
Pattern matching
def salutation(p: Person) =
(p.gender, p.maritalStatus) match {
case (Some(Male ), _ ) => "Mr."
case (Some(Female), Some(Single) ) => "Miss"
case (Some(Female), None ) => "Ms."
case (Some(Female), _ ) => "Mrs."
case _ => "Unknown"
}
Functions as 1st-class members
val people = Set(
Person("Niklaus", "Wirth", 80),
Person("Anders", "Hejlsberg", 53),
Person("Martin", "Odersky", 55),
Person("Kenneth", "Thompson", 71))
val toddlers = people.filter(person: Person => person.age <= 3)
val minors = people.filter(person => person.age < 18)
val seniorCitizens = people.filter(_.age >= 65)
val isSenior = { person: Person => person.age >= 65}
val alsoSeniorCitizens = people filter isSenior
No nulls
Scala urges us to declare a possible return value using the Option[T] monad; an
option can be either Some(value) or None, and allows us to assume to it can
never be null. We can use collection semantics to consume an Option[T].
case class Person(
firstName: Option[String],
lastName: Option[String],
age: Option[Int])
val completelyUnknown = Person(None, None, None)
val anonymousAdult = Person(None, None, Some(25))
val agelessPerson = Person(Some("John”), Some("Doe"), None)
def ageOf(p: Person): Int = p.age // Won't compile!
def unsafeAgeOf(p: Person): Int = p.age.get // What if age is unknown?
def ageOrZero(p: Person): Int = p.age.getOrElse(0)
Multiple Inheritance with Traits
Similar (but better than) Java 8’s interfaces with default
methods, a Scala class can extend multiple Traits; in case
of collision, the right-most trait wins.
Example: Logging
import org.slf4j._
class ClassWithLogs {
private val log = LoggerFactory.getLogger(this.getClass)
def getNormalizedName(person: Person) = {
log.info("getNormalizedName called")
log.debug("Normalizing " + person)
val normalizedName = person.firstName.toUpperCase.trim
log.debug("Normalized name is: " + normalizedName)
normalizedName
}
}
x1000 classes
Eagerly evaluated
Example: Logging
trait Logging {
private val log = LoggerFactory.getLogger(this.getClass)
protected def logInfo(message: => String) =
if (log.isInfoEnabled) log.info (message)
protected def logDebug(message: => String) =
if (log.isDebugEnabled) log.debug(message)
protected def logWarn(message: => String) =
if (log.isWarnEnabled) log.warn (message)
protected def logError(message: => String) =
if (log.isErrorEnabled) log.error(message)
}
By-name parameters
(lazily evaluated)
Demo Time!
Questions?
shaiy@wix.com
http://www.shaiyallin.com
@shaiyallin

Weitere ähnliche Inhalte

Was ist angesagt?

Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaEnsar Basri Kahveci
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako, Vasil Remeniuk
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In PracticeMichiel Borkent
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.Ruslan Shevchenko
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 

Was ist angesagt? (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 

Ähnlich wie Scala 101 overview of features, patterns, collections and functions

Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)mircodotta
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of JavascriptUniverse41
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to ProgrammingCindy Royal
 

Ähnlich wie Scala 101 overview of features, patterns, collections and functions (20)

scala-101
scala-101scala-101
scala-101
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Swift Basics
Swift BasicsSwift Basics
Swift Basics
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 

Kürzlich hochgeladen

Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxAS Design & AST.
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...kalichargn70th171
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxRTS corp
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 

Kürzlich hochgeladen (20)

Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptx
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 

Scala 101 overview of features, patterns, collections and functions

  • 1. Scala 101 Beyond Java: JVM FP, July 2014 Shai Yallin, Wix.com audience.filter(_.usesJava).foreach { member => sayHi(member) }
  • 2. A short overview of Scala’s features • A functional/OO programming language that runs on the JVM • Everything is an object – no primitive types • Functions are first-class members, every function is a value, including what is usually an operator* • Scala is statically-typed and supports type inference * Some of these are synthetic functions
  • 3. A short overview of Scala’s features • Lambda expressions, closures and currying naturally • Pattern matching • Multiple inheritance through Traits • Comprehensive collections library
  • 4. Determinism via Immutability Scala encourages everything to be immutable by default: • Variables (vals) • Collections • Value objects (using Case Classes)
  • 5. Better type safety • Scala is statically and strongly typed; type inference keeps the code lean and mean • Stricter generics (in comparison to Java) provide better compile- time checks • Advanced features include structural types and type aliases
  • 6. Case Classes Good software engineering makes use of value objects. These need to encapsulate the way they represent their state, to provide information hiding and to be easy to maintain. case class Person( firstName: String, lastName: String, age: Int) val authorOfPascal = Person("Niklaus", "Wirth", 80)
  • 7. Case classes give us: Factory methods Person("Niklaus", "Wirth", 80) Hashcode authorOfPascal.hashCode == 1423465897 Equals authorOfPascal.equals(authorOfModula) == true Copy val happyBirthday = authorOfPascal.copy(age = 81) Pattern matching Wait for it :-)
  • 8. Collections Some collection types: • Seq (abstract ordered sequence) • List (linked list) • Set (yeah, it’s a set) • Map (dictionary/hash) A collection can be: • Immutable / Mutable • Synchronous / Parallel
  • 9. Collections With type inference, trivial to instantiate val numbers = List(1, 2, 3) val numbers2 = 1 :: 2 :: 3 :: Nil val firstNames = Set("john", "mary", "muhammad”) val caloriesPer100gr = Map( "bacon" -> 541, "fries" -> 312, "lettuce" -> 15 )
  • 10. Collection functions++ ++: +: /: /: :+ :: ::: : addString aggregate andThen apply applyOrElse asInstanceOf canEqual collect collectFirst combinations companion compose contains containsSlice copyToArray copyToBuffer corresponds count diff distinct drop dropRight dropWhile endsWith exists filter filterNot find flatMap flatten fold foldLeft foldRight forall foreach genericBuilder groupBy grouped hasDefiniteSize head headOption indexOf indexOfSlice indexWhere indices init inits intersect isDefinedAt isEmpty isInstanceOf isTraversableAgain iterator last lastIndexOf lastIndexOfSlice lastIndexWhere lastOption length lengthCompare lift map mapConserve max maxBy min minBy mkString nonEmpty orElse padTo par partition patch permutations prefixLength product productArity productElement productIterator productPrefix reduce reduceLeft reduceLeftOption reduceOption reduceRight reduceRightOption repr reverse reverseIterator reverseMap reverse_::: runWith sameElements scan scanLeft scanRight segmentLength seq size slice sliding sortBy sortWith sorted span splitAt startsWith stringPrefix sum tail tails take takeRight takeWhile to toArray toBuffer toIndexedSeq toIterable toIterator toList toMap toSeq toSet toStream toString toTraversable toVector transpose union unzip unzip3 updated view withFilter
  • 11. Collection functions++ ++: +: /: /: :+ :: ::: : addString aggregate andThen apply applyOrElse asInstanceOf canEqual collect collectFirst combinations companion compose contains containsSlice copyToArray copyToBuffer corresponds count diff distinct drop dropRight dropWhile endsWith exists filter filterNot find flatMap flatten fold foldLeft foldRight forall foreach genericBuilder groupBy grouped hasDefiniteSize head headOption indexOf indexOfSlice indexWhere indices init inits intersect isDefinedAt isEmpty isInstanceOf isTraversableAgain iterator last lastIndexOf lastIndexOfSlice lastIndexWhere lastOption length lengthCompare lift map mapConserve max maxBy min minBy mkString nonEmpty orElse padTo par partition patch permutations prefixLength product productArity productElement productIterator productPrefix reduce reduceLeft reduceLeftOption reduceOption reduceRight reduceRightOption repr reverse reverseIterator reverseMap reverse_::: runWith sameElements scan scanLeft scanRight segmentLength seq size slice sliding sortBy sortWith sorted span splitAt startsWith stringPrefix sum tail tails take takeRight takeWhile to toArray toBuffer toIndexedSeq toIterable toIterator toList toMap toSeq toSet toStream toString toTraversable toVector transpose union unzip unzip3 updated view withFilter
  • 12. Pattern matching abstract class Gender case object Male extends Gender case object Female extends Gender abstract class MaritalStatus case object Single extends MaritalStatus case object Married extends MaritalStatus case object Divorced extends MaritalStatus case object Widowed extends MaritalStatus case class Person( firstName: String, lastName: String, age: Int, gender: Option[ Gender ], maritalStatus: Option[ MaritalStatus ])
  • 13. Pattern matching def salutation(p: Person) = (p.gender, p.maritalStatus) match { case (Some(Male ), _ ) => "Mr." case (Some(Female), Some(Single) ) => "Miss" case (Some(Female), None ) => "Ms." case (Some(Female), _ ) => "Mrs." case _ => "Unknown" }
  • 14. Functions as 1st-class members val people = Set( Person("Niklaus", "Wirth", 80), Person("Anders", "Hejlsberg", 53), Person("Martin", "Odersky", 55), Person("Kenneth", "Thompson", 71)) val toddlers = people.filter(person: Person => person.age <= 3) val minors = people.filter(person => person.age < 18) val seniorCitizens = people.filter(_.age >= 65) val isSenior = { person: Person => person.age >= 65} val alsoSeniorCitizens = people filter isSenior
  • 15. No nulls Scala urges us to declare a possible return value using the Option[T] monad; an option can be either Some(value) or None, and allows us to assume to it can never be null. We can use collection semantics to consume an Option[T]. case class Person( firstName: Option[String], lastName: Option[String], age: Option[Int]) val completelyUnknown = Person(None, None, None) val anonymousAdult = Person(None, None, Some(25)) val agelessPerson = Person(Some("John”), Some("Doe"), None) def ageOf(p: Person): Int = p.age // Won't compile! def unsafeAgeOf(p: Person): Int = p.age.get // What if age is unknown? def ageOrZero(p: Person): Int = p.age.getOrElse(0)
  • 16. Multiple Inheritance with Traits Similar (but better than) Java 8’s interfaces with default methods, a Scala class can extend multiple Traits; in case of collision, the right-most trait wins.
  • 17. Example: Logging import org.slf4j._ class ClassWithLogs { private val log = LoggerFactory.getLogger(this.getClass) def getNormalizedName(person: Person) = { log.info("getNormalizedName called") log.debug("Normalizing " + person) val normalizedName = person.firstName.toUpperCase.trim log.debug("Normalized name is: " + normalizedName) normalizedName } } x1000 classes Eagerly evaluated
  • 18. Example: Logging trait Logging { private val log = LoggerFactory.getLogger(this.getClass) protected def logInfo(message: => String) = if (log.isInfoEnabled) log.info (message) protected def logDebug(message: => String) = if (log.isDebugEnabled) log.debug(message) protected def logWarn(message: => String) = if (log.isWarnEnabled) log.warn (message) protected def logError(message: => String) = if (log.isErrorEnabled) log.error(message) } By-name parameters (lazily evaluated)

Hinweis der Redaktion

  1. Statically typed – types are checked in compile time verses runtime Strongly typed - each variable must have a concrete type You get the best of both worlds – lean code like in dynamic languages and compile-time checking of adherence to structure Type inference can slow down compilation – use with care Structural types – the canonical example is closeable
  2. A case class automatically makes its constructor arguments into vals. It also provides automatic equals, hashCode, toString methods and a very useful copy method which makes use of Scala’s named arguments (with defaults) feature. We also see that case classes with proper default argument values are essentially test object builders, which saves us tons of code for test setup