SlideShare a Scribd company logo
Scala for Java Devs
Christos KK Loverdos
loverdos at github, twitter, gmail
Java meetup @ Thessaloniki
2017‐10‐12
Java meetup @ Thessaloniki - 2017-10-12
About me
Software engineer, nearly 20 years now
Architect, team lead, technical PM
Telcos, startups
employee, freelancer, consultant
Java enthusiast since 1997
Scala enthusiast since 2004 (2007)
Co-author of "Steps in Scala"
Java meetup @ Thessaloniki - 2017-10-12 2
A very incomplete  meline
2004 v1.0
2006 v2.0
2007 v2.7 (+Li web framework)
2010 v2.8 (+ScalaDays @ EPFL, 180 participants)
2011 v2.9
2012 v2.10
now v2.12 (+Java 8 interoperability)
Java meetup @ Thessaloniki - 2017-10-12 3
Main ideas ‐ Why Scala?
Synthesis of OOP and FP
Being scalable
Programming in the small vs programming in
the large
Provide the right abstractions in the core,
everything else in libraries
Rich type system
Java meetup @ Thessaloniki - 2017-10-12 4
A few highlights
Immutable objects and collections
Type inference
Func ons are rst-class
Everything is an object
Pattern matching
Domain Speci c Languages
REPL
Java meetup @ Thessaloniki - 2017-10-12 5
Warm‐up
Java meetup @ Thessaloniki - 2017-10-12 6
Hello world
hello.scala
object hello {
def main(args: Array[String]): Unit =
println("Hello world")
}
Java meetup @ Thessaloniki - 2017-10-12 7
Hello world
hello.scala
object hello {
def main(args: Array[String]): Unit =
println("Hello world")
}
$ scala -save hello.scala
Hello world
Java meetup @ Thessaloniki - 2017-10-12 8
Hello world
hello.scala
object hello {
def main(args: Array[String]): Unit =
println("Hello world")
}
$ scala -save hello.scala
Hello world
$ ls hello.*
hello.jar hello.scala
Java meetup @ Thessaloniki - 2017-10-12 9
Hello world Scala vs Java
object hello {}
public class hello {}
object, class
No public
Java meetup @ Thessaloniki - 2017-10-12 10
Hello world Scala vs Java
def main(...): Unit = {}
public static void main(...) {}
Unit vs void
No sta c
Return type a er vs before method name & args
Scala object implies Java sta c
Java meetup @ Thessaloniki - 2017-10-12 11
Hello world Scala vs Java
args: Array[String]
String[] args
Type a er vs before the name
Java meetup @ Thessaloniki - 2017-10-12 12
Hello world Scala vs Java
args: Array[String]
String[] args
Type a er vs before the name
DIM X AS INTEGER
VAR X: Integer
Java meetup @ Thessaloniki - 2017-10-12 13
REPL: a value is an object
Java meetup @ Thessaloniki - 2017-10-12 14
A simple class
class Complex(val re: Double, val im: Double) {
def this() = this(0, 0)
def mag = Math.sqrt(re*re + im*im)
def polarCoordinates = {
val r = Math.sqrt(re*re + im*im)
val phi = Math.atan2(im, re)
(r, phi)
}
override def toString = s"Complex($re, $im)"
}
Java meetup @ Thessaloniki - 2017-10-12 15
A simple class
class Complex(val re: Double, val im: Double) {
def this() = this(0, 0)
def mag: Double = Math.sqrt(re*re + im*im)
def polarCoordinates: (Double, Double) = {
val r = Math.sqrt(re*re + im*im)
val phi = Math.atan2(im, re)
(r, phi)
}
override def toString: String = s"Complex($re, $im)"
}
Java meetup @ Thessaloniki - 2017-10-12 16
Super constructor
class Animal(name: String)
class Dog(name: String) extends Animal(name)
Java meetup @ Thessaloniki - 2017-10-12 17
Some more fun
Java meetup @ Thessaloniki - 2017-10-12 18
Trait (interface)
trait Printer {
def printPDF(pdf: File): Unit
def printRTF(rtf: File): Unit = {
val pdf = ... // convert RTF to PDF
printPDF(pdf)
}
}
Using default methods
(https://github.com/scala/scala/pull/5003)
as of Scala 2.12
Java meetup @ Thessaloniki - 2017-10-12 19
Trait (mixin)
trait Mage {
def castSpell(spell: Spell, target: Target) = ...
}
trait Fighter {
def useSword(target: Target) = ...
}
class Player1 extends Mage
class Player2 extends Mage with Fighter
Java meetup @ Thessaloniki - 2017-10-12 20
Case class
case class Complex(re: Double, im: Double)
Java meetup @ Thessaloniki - 2017-10-12 21
Case class
case class Complex(re: Double, im: Double)
val c = new Complex(1.2, 2.0)
val cc = Complex(1.2, 2.0)
No need to use new
Java meetup @ Thessaloniki - 2017-10-12 22
Case class
case class Complex(re: Double, im: Double)
val c = new Complex(1.2, 2.0)
val cc = Complex(1.2, 2.0)
// (c == cc) is true
Automatic, derived, structural equality
Compiler implements hashCode and equals
Very handy for immutable domain objects
Java meetup @ Thessaloniki - 2017-10-12 23
Case class
case class Complex(re: Double, im: Double)
// instead of
// case class Complex(val re: Double, val im: Double)
Constructor arguments are promoted to class
attributes
Java meetup @ Thessaloniki - 2017-10-12 24
Case class
case class Complex(re: Double, im: Double)
val zero = Complex(0, 0)
val one = zero.copy(re = 1)
val i = zero.copy(im = 1)
Builtin copy()
Java meetup @ Thessaloniki - 2017-10-12 25
Case class ‐ Pa ern matching
case class Complex(re: Double, im: Double)
val c: Complex = ...
c match {
case Complex(0, 0) => // zero
case Complex(1, 0) => // real unit
case Complex(0, 1) => // imaginary unit
case Complex(a, b) if a == b => // equal coordinates
case Complex(a, b) => // all other cases ...
}
Java meetup @ Thessaloniki - 2017-10-12 26
Case class ‐ ASTs
ast.scala
sealed trait AstNode
case class Expr(n: Number) extends AstNode
case class Add(left: Expr, right: Expr) extends AstNode
other.scala
val x: AstNode = parseSourceCode(...)
x match {
case Expr(n) => ...
case Add(left, right) => ...
}
Java meetup @ Thessaloniki - 2017-10-12 27
Generics
type parameter in a class
trait Ordered[T] {
def < (that: T): Boolean
def <=(that: T): Boolean
...
}
class ANumber(x: Int) extends Ordered[ANumber] { ... }
Ordered[T] characterizes a type T that has a single,
natural ordering.
Java meetup @ Thessaloniki - 2017-10-12 28
Generics
Collections
final class Array[T] // mutable
sealed abstract class List[T] // immutable
val a = Array(1, 2, 3)
val b = List(1, 2, 3)
val c = 1 :: 2 :: 3
Java's Collection<T> becomes Collection[T]
Java meetup @ Thessaloniki - 2017-10-12 29
digression: List again
Java meetup @ Thessaloniki - 2017-10-12 30
digression: List again
sealed abstract class List[+A] extends AbstractSeq[A]
with LinearSeq[A]
with Product
with GenericTraversableTemplate[A, List]
with LinearSeqOptimized[A, List[A]]
with Serializable
Java meetup @ Thessaloniki - 2017-10-12 31
Generics (method)
Parametric polymorphism
object Sorter {
def quickSort[T](elems: Array[T], /*what else?*/)
}
Java meetup @ Thessaloniki - 2017-10-12 32
Now that we've talked about
generics, let's talk about
func ons
Java meetup @ Thessaloniki - 2017-10-12 33
Func on (defini on)
trait Function1[-A, +B] extends AnyRef {
def apply(a: A): B
}
Java meetup @ Thessaloniki - 2017-10-12 34
Func on (defini on)
trait Function1[A, B] {
def apply(a: A): B
}
We can also represent the type Function1[A, B] as
A => B or
(A) => B
This is a total function
Java meetup @ Thessaloniki - 2017-10-12 35
Func on
Math:
f : A → B
Scala:
f: A => B
f: Function1[A, B]
Java:
Function1<A, B> f
Java meetup @ Thessaloniki - 2017-10-12 36
Func on (declara on)
val s_length:
(String) => Int =
(s: String) => s.length
Notice how the method length of class String was
promoted to a function.
Java meetup @ Thessaloniki - 2017-10-12 37
Func on (declara on)
val s_length: (String) => Int = s => s.length
// or
val s_length: (String) => Int = _.length
With some nice syntactic sugar
Java meetup @ Thessaloniki - 2017-10-12 38
Func on (applica on)
We apply a function f of type A => B
val f: A => B = ...
to a value of type A
val x: A = ...
using intuitive syntax
f(x)
Java meetup @ Thessaloniki - 2017-10-12 39
Func on (applica on)
... which gets desugared to
f.apply(x)
Remember that Function1 is de ned with one
method:
trait Function1[A, B] {
def apply(a: A): B
}
Java meetup @ Thessaloniki - 2017-10-12 40
Func on (applica on)
... which gets desugared to
f.apply(x)
Everything is an object
Java meetup @ Thessaloniki - 2017-10-12 41
Func on (applica on)
apply is a binary method and you can also write
f apply x
Same thing for computing e.g. the maximum of two
integers
x max y vs x.max(y)
Java meetup @ Thessaloniki - 2017-10-12 42
Collec ons + Func ons = fun
Java meetup @ Thessaloniki - 2017-10-12 43
map
Map each element of a collection to a new
element, according to a well de ned function
trait Collection[A] {
def map[B](f: A => B): Collection[B]
}
Java meetup @ Thessaloniki - 2017-10-12 44
map
Map each element of a collection to a new
element, according to a well de ned function
trait Collection[A] {
def map[B](f: A => B): Collection[B]
}
scala> List("a", "bb").map(x => x.length)
res2: List[Int] = List(1, 2)
Java meetup @ Thessaloniki - 2017-10-12 45
map
Map each element of a collection to a new
element, according to a well de ned function
trait Collection[A] {
def map[B](f: A => B): Collection[B]
}
scala> List(1, 2, 3).map( n => isOdd(n) )
res3: List[Boolean] = List(true, false, true)
Java meetup @ Thessaloniki - 2017-10-12 46
map
Map each element of a collection to a new
element, according to a well de ned function
trait Collection[A] {
def map[B](f: A => B): Collection[B]
}
alist.map(x => isOdd(x))
alist.map( isOdd(_) )
alist.map( isOdd )
alist map isOdd
Java meetup @ Thessaloniki - 2017-10-12 47
... from map to Map
The generic type is Map[A, B]
The default implementation is immutable
val numbers: Map[Int, String] = Map()
or
val numbers = Map[Int, String]()
Java meetup @ Thessaloniki - 2017-10-12 48
... from map to Map
Initialization is not verbose
val numbers = Map[Int, String](
1 -> "one",
2 -> "two",
3 -> "three"
)
Java meetup @ Thessaloniki - 2017-10-12 49
... and then to groupBy
Now that we have Lists and Maps
scalal> val list = List(1, 2, 3)
list: List[Int] = List(1, 2, 3)
scala> val isOdd = (x: Int) => x % 2 == 1
isOdd: Int => Boolean = <function>
scala> val oddeven = list.groupBy(isOdd)
oddeven: scala.collection.immutable.Map[Boolean,List[Int]] =
Map(false -> List(2), true -> List(1, 3))
Java meetup @ Thessaloniki - 2017-10-12 50
What is the type of groupBy?
Java meetup @ Thessaloniki - 2017-10-12 51
What is the type of groupBy?
class List[A] {
def groupBy ...
}
Java meetup @ Thessaloniki - 2017-10-12 52
What is the type of groupBy?
class List[A] {
def groupBy[B](f: A => B): ???
}
Java meetup @ Thessaloniki - 2017-10-12 53
What is the type of groupBy?
class List[A] {
def groupBy[B](f: A => B): Map[B, List[A]]
}
Java meetup @ Thessaloniki - 2017-10-12 54
null = Billion dollar mistake
Java meetup @ Thessaloniki - 2017-10-12 55
Op on
trait Option[+T]
case class Some[T](t: T) extends Option[T]
case object None extends Option[Nothing]
Nothing is a subtype of every other type but it has no
instances
Java meetup @ Thessaloniki - 2017-10-12 56
Op on
scala> val xOpt: Option[Complex] = Option(null)
xOpt: Option[Complex] = None
scala> val x = xOpt.getOrElse(Complex(0, 0))
x: Complex = Complex(0.0,0.0)
Java meetup @ Thessaloniki - 2017-10-12 57
Op on (pa ern match)
xOpt match {
case Some(Complex(re, im)) => ...
case None =>
}
Java meetup @ Thessaloniki - 2017-10-12 58
Op on (for comprehension)
for {
x <- xOpt
} { ... }
If we only care about the Some() case.
In effect, you can view Option as a simple
collection of at most one item.
Java meetup @ Thessaloniki - 2017-10-12 59
For comprehension
for {
item <- List(1, 2, 3)
} yield item * 2
Computes a new list with each item doubled.
This is a map in disguise.
Java meetup @ Thessaloniki - 2017-10-12 60
For comprehension
for {
item <- List(1, 2, 3)
} yield item * 2
same as
List(1, 2, 3).map(_ * 2)
Java meetup @ Thessaloniki - 2017-10-12 61
For comprehension
for {
item <- List(1, 2, 3)
} yield item * 2
same as
List(1, 2, 3).map(_ * 2)
Remember that
List(1, 2, 3).map(x => x * 2)
Java meetup @ Thessaloniki - 2017-10-12 62
Add some more ingredients,
and then you get
Java meetup @ Thessaloniki - 2017-10-12 63
?
Java meetup @ Thessaloniki - 2017-10-12 64
Monads! (in another talk)
for {
x <- Some(Complex(0.0, 1.0))
m <- List(1.0, 2.0, 3.0)
} yield Complex(x.re * m, x.im * m)
Java meetup @ Thessaloniki - 2017-10-12 65
Monads! (in another talk)
for {
x <- Some(Complex(0.0, 1.0))
m <- List(1.0, 2.0, 3.0)
} yield Complex(x.re * m, x.im * m)
What about this?
for {
x <- None
m <- List(1.0, 2.0, 3.0)
} yield Complex(x.re * m, x.im * m)
Java meetup @ Thessaloniki - 2017-10-12 66
And since we are talking
about op onal things ...
Java meetup @ Thessaloniki - 2017-10-12 67
Op onal arguments (class)
case class Collector(
name: String,
coins: List[Coin] = List()
books: List[Book] = List() // = Nil
)
Java meetup @ Thessaloniki - 2017-10-12 68
Op onal arguments (class)
case class Collector(
name: String,
coins: List[Coin] = List()
books: List[Book] = List() // = Nil
)
val collector1 = Collector(
"John Smith"
)
Java meetup @ Thessaloniki - 2017-10-12 69
Op onal arguments (class)
case class Collector(
name: String,
coins: List[Coin] = List()
books: List[Book] = List() // = Nil
)
val collector2 = Collector(
"John Smith",
List(OneEuroCoin),
List(Book("Lord of the rings"))
)
Java meetup @ Thessaloniki - 2017-10-12 70
Op onal arguments (class)
case class Collector(
name: String,
coins: List[Coin] = List()
books: List[Book] = List() // = Nil
)
val collector2 = Collector(
name = "John Smith",
coins = List(OneEuroCoin),
books = List(Book("Lord of the rings"))
)
Java meetup @ Thessaloniki - 2017-10-12 71
Not covered
Java meetup @ Thessaloniki - 2017-10-12 72
Easy stuff
Try[T] data type
Future[T] data type
lazy values
by-name parameters
...
Java meetup @ Thessaloniki - 2017-10-12 73
Not so easy stuff
Variance (covariance, contravariance)
List[+T]
Type constructors, higher kinds
(very informally)
List : T → List[T]
Implicits
real power (cf. Haskell type classes).
Java meetup @ Thessaloniki - 2017-10-12 74
Epilogue
Java meetup @ Thessaloniki - 2017-10-12 75
Opinions circa 2009
"If I were to pick a language to use today other
than Java, it would be Scala"
James Gosling, creator of Java
"If someone had shown me the 'Programming in
Scala' book back in 2003, I'd probably have never
created Groovy"
James Strachan, creator of Groovy
Java meetup @ Thessaloniki - 2017-10-12 76
Resources
scala-lang.org
google.com/search?q=awesome-scala
github.com/trending/scala
Java meetup @ Thessaloniki - 2017-10-12 77
Thank you!
Java meetup @ Thessaloniki - 2017-10-12 78
Slides that did not survive
Java meetup @ Thessaloniki - 2017-10-12 79
BEGIN warm‐up
Java meetup @ Thessaloniki - 2017-10-12 80
END warm‐up
Java meetup @ Thessaloniki - 2017-10-12 81
BEGIN war map
Java meetup @ Thessaloniki - 2017-10-12 82
END war map
Java meetup @ Thessaloniki - 2017-10-12 83
Where to find me
select username
from venue
where username = 'loverdos'
and venuename in ('gmail', 'twitter', 'github')
Java meetup @ Thessaloniki - 2017-10-12 84

More Related Content

PDF
Demystifying functional programming with Scala
PDF
Scala: Object-Oriented Meets Functional, by Iulian Dragos
PDF
Railroading into Scala
PDF
Functional Programming in Scala
PDF
Spark workshop
PDF
Getting Started With Scala
ODP
Introducing scala
PPT
An introduction to scala
Demystifying functional programming with Scala
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Railroading into Scala
Functional Programming in Scala
Spark workshop
Getting Started With Scala
Introducing scala
An introduction to scala

What's hot (20)

PPT
Claire98
PDF
Scala categorytheory
PDF
scalaliftoff2009.pdf
PDF
Scala 2013 review
KEY
Scala clojure techday_2011
PDF
Pragmatic Real-World Scala (short version)
PDF
Scala collections
PDF
Approximation Data Structures for Streaming Applications
PDF
Sets, maps and hash tables (Java Collections)
PDF
Scala for Java Programmers
PDF
Spark 4th Meetup Londond - Building a Product with Spark
PDF
Scala Bootcamp 1
PDF
The Scala Programming Language
PDF
Lecture 5: Functional Programming
PDF
Introduction à Scala - Michel Schinz - January 2010
PDF
Scala taxonomy
PDF
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
PDF
Libretto
PPTX
Scala meetup - Intro to spark
PDF
Functional and Algebraic Domain Modeling
Claire98
Scala categorytheory
scalaliftoff2009.pdf
Scala 2013 review
Scala clojure techday_2011
Pragmatic Real-World Scala (short version)
Scala collections
Approximation Data Structures for Streaming Applications
Sets, maps and hash tables (Java Collections)
Scala for Java Programmers
Spark 4th Meetup Londond - Building a Product with Spark
Scala Bootcamp 1
The Scala Programming Language
Lecture 5: Functional Programming
Introduction à Scala - Michel Schinz - January 2010
Scala taxonomy
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
Libretto
Scala meetup - Intro to spark
Functional and Algebraic Domain Modeling
Ad

Similar to Scala for Java Devs (20)

PDF
Introduction to Scala : Clueda
PDF
Scala Paradigms
PDF
Introduction to Scala
PDF
Scala for Java Developers - Intro
PDF
Scala Collections : Java 8 on Steroids
PDF
Programming in Scala - Lecture Three
PDF
Miles Sabin Introduction To Scala For Java Developers
PDF
A Brief Introduction to Scala for Java Developers
PDF
An Introduction to Scala for Java Developers
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
PDF
Scala for Java Developers (Silicon Valley Code Camp 13)
PDF
Invitation to Scala
PPTX
Programming picaresque
PDF
Meet scala
PDF
Getting Started With Scala
PDF
(How) can we benefit from adopting scala?
PPTX
Introduction to kotlin + spring boot demo
PDF
Scala @ TechMeetup Edinburgh
PDF
Kotlin: Challenges in JVM language design
PDF
Stepping Up : A Brief Intro to Scala
Introduction to Scala : Clueda
Scala Paradigms
Introduction to Scala
Scala for Java Developers - Intro
Scala Collections : Java 8 on Steroids
Programming in Scala - Lecture Three
Miles Sabin Introduction To Scala For Java Developers
A Brief Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Scala for Java Developers (Silicon Valley Code Camp 13)
Invitation to Scala
Programming picaresque
Meet scala
Getting Started With Scala
(How) can we benefit from adopting scala?
Introduction to kotlin + spring boot demo
Scala @ TechMeetup Edinburgh
Kotlin: Challenges in JVM language design
Stepping Up : A Brief Intro to Scala
Ad

Recently uploaded (20)

PPTX
Introduction to Artificial Intelligence
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
medical staffing services at VALiNTRY
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
history of c programming in notes for students .pptx
PDF
AI in Product Development-omnex systems
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPT
Introduction Database Management System for Course Database
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Introduction to Artificial Intelligence
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
How to Migrate SBCGlobal Email to Yahoo Easily
PTS Company Brochure 2025 (1).pdf.......
medical staffing services at VALiNTRY
Which alternative to Crystal Reports is best for small or large businesses.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Softaken Excel to vCard Converter Software.pdf
CHAPTER 2 - PM Management and IT Context
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Upgrade and Innovation Strategies for SAP ERP Customers
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
history of c programming in notes for students .pptx
AI in Product Development-omnex systems
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Odoo Companies in India – Driving Business Transformation.pdf
Introduction Database Management System for Course Database
ManageIQ - Sprint 268 Review - Slide Deck
Adobe Illustrator 28.6 Crack My Vision of Vector Design

Scala for Java Devs