SlideShare a Scribd company logo
1 of 63
Download to read offline
training@instil.co
© Instil Software 2020
The Great Scala Makeover
@GarthGilmour
https://bitbucket.org/GarthGilmour/scala3-bash-feb2020
Me
C
C++
Java
C#
Pascal
Delphi
Basic
Visual Basic
VB .NET
Perl
F#
JavaScript
1990
2000
2010
TypeScript
PowerShell
Dart
Scala
Clojure
Kotlin
Groovy
Objective C
Shell
Scripting
Swift
Python
Ruby
ReasonML
Go
Rust
D
Scala – The Early Days
Scala – The Early Days
Scala – The Early Days
Enter Dotty
Dotty is the codename for the new Scala compiler
• It has been rewritten from scratch for speed and correctness
The language has been simplified and extended for Dotty
• Unpopular and redundant features have been removed
• New features reflect the increasing importance of FP
• Implicits and macros remain, but in a new way
Enter Dotty
There is a new intermediate format
• Your Scala 3 code compiles into TASTy
• Short for Typed Abstract Syntax Trees
• We then generate JS, Bytecode etc..
You can reflect on TASTY Syntax Trees
• This is how macros are implemented
Enter Dotty
How To Try Out Scala 3
brew install sbt
brew install lampepfl/brew/dotty
Install VS Code and add to PATH
• https://code.visualstudio.com/docs/setup/mac#_command-line
sbt new lampepfl/dotty.g8
• Enter the info the wizard requires
Change directory into project folder
sbt launchIDE
How To Try Out Scala 3
Name Notes
XML Literals Believe it or not this was once a great idea
Delayed Init This partially breaks the ‘App’ class
Procedure Syntax Writing ‘def foo() { … }’ no longer declares a return type of Unit
The Do While Loop What?
Existential Types
Class Shadowing
Symbol Literals
Auto Application
Weak Conformance
Compound Types
Auto Tupling
[this] Qualifier
Stuff That Dies
def fakingDoWhile() = {
println("Output from first weird loop...")
while({
val x = Math.random()
println(s"t$x")
x > 0.5
})()
println("Output from second weird loop...")
while {
val x = Math.random()
println(s"t$x")
x > 0.5
} do ()
}
Output from first weird loop...
0.6506029560584671
0.4481933779924502
Output from second weird loop...
0.9451875748422434
0.5031857996404466
0.5923768910372654
0.8600801357886065
0.536180700764455
0.7337064700795435
0.7930386780841578
0.2882381886829134
No Do…While Loops
Anything can be declared at the top level
• Including Types, Variables and Functions
• You no longer need package objects
Any function can be main
• By annotating with with ‘@main’
Top Level Declarations
val menu = ""”
Pick an option:
1) Creator applications
2) Extension methods
3) Basic enumerations
4) Enumerations as ADTs
"""
@main def foobar(): Unit = {
var notDone = true
while(notDone) {
println(menu)
val choice = scala.io.StdIn.readInt()
choice match {
case 1 => creatorApplications()
case 2 => extensionMethods()
case _ => notDone = false
}
}
}
Pick an option:
1) Creator applications
2) Extension methods
3) Basic enumerations
4) Enumerations as ADTs
1
Jane aged 25
Dave aged 27
Top Level Declarations
package foo
def *() = println("Hello dere...")
Hello dere...
A Fun Obfuscation
package bar
import foo.*
@main def bar() = *()
You could always avoid ‘new’ in Scala via an ‘apply’ method
• But it would be laborious to do this for every type in your model
Scala 3 makes it trivial to avoid new in almost all cases
This is done by adding a fourth way of interpreting a function:
This is referred to as ‘Creator Applications’
Creator Applications
[Given f(args)] if f is syntactically a stable
identifier, and new f where f is interpreted
as a type identifier is applicable to args,
continue with new f(args)
class Person(name: String, age: Int) {
def this(name: String) = this(name, 27)
override def toString() = s"$name aged $age"
}
def creatorApplications() = {
val p1 = Person("Jane", 25)
val p2 = Person("Dave")
println(p1)
println(p2)
}
Jane aged 25
Dave aged 27
Creator Applications
Scala 3 supports extensions to existing types
• Useful when you don’t have the source or don’t want to modify it
Extension methods can be defined singly or in groups
• The latter is referred to as a collective extension
Extensions can be operators and can be applied to generic types
Extension Methods
def (s: String).times2() = s + s
extension on (s: String) {
def times3() = s + s + s
def times4() = s + s + s + s
}
def extensionMethods() = {
val s1 = "Wibble"
println(s1.times2())
println(s1.times3())
println(s1.times4())
}
WibbleWibble
WibbleWibbleWibble
WibbleWibbleWibbleWibble
Extension Methods
Scala finally does Enums!
• These were not available previously
• The idea was to use Case Classes
You can extend ‘java.lang.Enum’
• For interoperability with Java
Enums can have type parameters
• Giving you an easy way to do ADTs
Enumerations J
enum Direction {
case NORTH, SOUTH, EAST, WEST
def printArrow() = {
var arrow = '?’
this match {
case WEST => arrow = 0x2190
case EAST => arrow = 0x2192
case NORTH => arrow = 0x2191
case SOUTH => arrow = 0x2193
}
println(arrow)
}
}
def basicEnumerations() = {
val d = Direction.NORTH
print(d)
d.printArrow()
}
NORTH↑
Enumerations J
Does Anything About This Feel Familiar?
Scala Verses Kotlin
“There’s something I ought to tell you”
“Tell me”
“I don’t use the new keyword either”
“I don’t use implicits either”
“I also have enumerated types”
“I also have extension methods”
“I can declare top level types”
Vs
The new enumeration syntax makes it easy to create ADT’s
• As in particular generic ADT’s like Option, Try and Either
You could always do this with Case Classes
• But the process is simplified to reflect their increasing relevance
Enumerations as ADTs
enum Try[+T] {
case Success(val result: T) extends Try[T]
case Failure(val error: String) extends Try[Nothing]
def fold(errorHandler: String => Unit,
resultHandler: T => Unit) = {
this match {
case Success(result) => resultHandler(result)
case Failure(error) => errorHandler(error)
}
}
}
def readPropertyAsInt(name: String): Try[Int] = {
val propertyValue = System.getProperty(name)
try {
Try.Success(Integer.parseInt(propertyValue))
} catch {
case ex: NumberFormatException => Try.Failure(ex.getMessage)
}
}
Enumerations as ADTs
def enumerationsAsADTs() = {
System.setProperty("testProp", "123")
val result1 = readPropertyAsInt("testProp")
val result2 = readPropertyAsInt("java.vendor")
result1.fold(
msg => println(s"Whoops - $msg"),
num => println(s"Hurrah - $num")
)
result2.fold(
msg => println(s"Whoops - $msg"),
num => println(s"Hurrah - $num")
)
}
Hurrah - 123
Whoops - For input string: "AdoptOpenJDK"
Enumerations as ADTs
Scala 3 adds support for:
• Union Types
• Intersection Types
• Literal Types
• Opaque Type Aliases
This gives a richer toolkit for describing data
• Fans of DDD should be very happy
New Ways To Manipulate Types
Parameters in Scala 3 can be defined as unions of types
• Where the types don’t have to share a common base class
For example ‘def foo(input: Foo | Bar | Zed)’
This will also work with literals
Union Types
case class WorkExperience(val years: Int)
case class Degree(val subject: String)
case class Publication(val isbn: String)
def employ(name: String, reason: Degree | WorkExperience | Publication) = {
print(s"Employing $name because of ")
reason match {
case Degree(subject) => println(s"their degree in $subject")
case WorkExperience(years) => println(s"their $years years experience")
case Publication(_) => println("they wrote a book")
}
}
Union Types
employ("Dave", Degree("Physics"))
employ("Jane", WorkExperience(10))
employ("Fred", Publication("ABC-123"))
Employing Dave because of their degree in Physics
Employing Jane because of their 10 years experience
Employing Fred because of they wrote a book
Union Types
Parameters can also be the intersection of multiple types
• Where a type must extend multiple traits
For example ‘def foo(input: Foo & Bar & Zed)’
Intersection Types
trait Edible {
def eat(): Unit
}
trait Drinkable {
def drink(): Unit
}
class Apple extends Edible {
override def eat() = println("Eating an Apple")
}
class Milk extends Drinkable {
override def drink() = println("Drinking some Milk")
}
class Soup extends Edible with Drinkable {
override def eat() = println("Eating Soup")
override def drink() = println("Drinking Soup")
}
Intersection Types
def intersectionTypes() = {
def eatDrinkAndBeMerry(input: Edible & Drinkable) = {
input.eat()
input.drink()
}
//eatDrinkAndBeMerry(Apple()) //Will not compile
//eatDrinkAndBeMerry(Milk()) //Will not compile
eatDrinkAndBeMerry(Soup())
}
Eating Soup
Drinking Soup
Intersection Types
Literal Types started in Dotty but were backported to 2.13
• They allow you to treat any literal value as a type in its own right
• 1, 2.3, “ABC” can all be used as types with a singleton instance
These are especially powerful when combined with Union Types
• E.g. the input to a method can be constrained to the names of events
Literal Types
def literalTypes() = {
def specialFunction(input: "abc" | "def" | "ghi") = println(input)
val specialNumber: 123 = 123
val specialOption: Option[456] = Option(456)
specialFunction("def")
specialFunction("ghi")
//specialFunction("xyz") //Will not compile
println(specialNumber)
println(specialOption.getOrElse(0))
}
def
ghi
123
456
Literal Types
Opaque type aliases provide abstraction without overhead
Let’s say you want to have an ‘ItemID’ type
• Which can be expressed as a regular String
You are concerned about erroneous conversions
• E.g. ‘addItem(“Toaster”)’ instead of ‘addItem(“AB12”)’
One option would be to create a wrapper type
• An ‘ItemID’ class with a single field of type String
• But this would introduce the overhead of (un)boxing
Type aliases provide a neat solution
Opaque Type Aliases
package demo
import scala.collection.mutable.Stack
opaque type ItemID = String
object ItemID {
def apply(str: String): ItemID = str
}
class Shop {
val purchases = Stack[ItemID]()
def buy(item: ItemID) = purchases.push(item)
override def toString() = purchases.toString()
}
Opaque Type Aliases
import demo.Shop
import demo.ItemID
def opaqueTypeAliases() = {
val shop = new Shop()
//shop.buy("AB12") //Will Not Compile
val item1: ItemID = ItemID("AB12")
shop.buy(item1)
shop.buy(ItemID("CD34"))
shop.buy(ItemID("EF56"))
println(shop)
}
Stack(EF56, CD34, AB12)
Opaque Type Aliases
Does Anything About This Feel Familiar?
Does Anything About This Feel Familiar?
Scala Verses F#
“There’s something I ought to tell you”
“Tell me”
“I don’t need wrapper types either”
“I also support union types”
Vs
Significant Whitespace
This one was a shock
• …and it is still taking a while to percolate
Scala 3 supports significant whitespace
• If you omit the parenthesis at the start of a
function then whitespace is used instead
• All the conditionals and loops have a new
form that does not need parenthesis
@main def foobar(): Unit =
var notDone = true
while notDone do
println(menu)
val choice = scala.io.StdIn.readInt()
choice match
case 1 => creatorApplications()
case 2 => extensionMethods()
case _ => notDone = false
Significant Whitespace
@main def foobar(): Unit = {
var notDone = true
while(notDone) {
println(menu)
val choice = scala.io.StdIn.readInt()
choice match {
case 1 => creatorApplications()
case 2 => extensionMethods()
case _ => notDone = false
}
}
}
Does Anything About This Feel Familiar?
Scala Verses Python
“There’s something I ought to tell you”
“Tell me”
“I don’t use braces either”
Vs
Collections have always been a strong point for Scala
• Despite complaints that they are too pure or should be purer J
There were improvements in 2.13 which are continued into to 3.0
• New methods have been added and the implementation is simplified
Improved Collections
enum Rating {
case GREAT, BRILLIANT, SUPERB, LIFE_CHANGING
}
class Movie(val title: String,
val rating: Rating,
val releaseDate: LocalDate,
val quotes: List[String])
def greatActionMovies(): List[Movie] = List(
Movie("Predator",
Rating.LIFE_CHANGING,
of(1987, JUNE, 12),
List("Get to the Chopper!",
"Stick around.",
"If it bleeds, we can kill it.",
"He's using the trees.",
"We move, five meter spread, no sound.")),
Movie(...),
Improved Collections
def triplesOfQuotes(title: String) = {
val movies = greatActionMovies()
println(s"All possible triples of $title quotes")
movies.find(_.title == title)
.map(m => m.quotes.combinations(3))
.fold(println("Not found!"))(_.foreach(println))
}
triplesOfQuotes("Commando")
All possible triples of Commando quotes
List(I have to remind you Sully, this is my weak arm!,
I eat Green Berets for breakfast. And right now, I'm very hungry!,
Don't disturb my friend, he's dead tired.)
List(...)
List(...)
List(...)
List(...)
Improved Collections
def movieTitlesByMonthReleased() = {
val movies = greatActionMovies()
println("Movie titles grouped by month of release")
movies.groupMap(_.releaseDate.getMonth)(_.title)
.foreach(row => {
val(month, titles) = row
print(s"tMovies released in $month: ")
titles.foreach(t => print(s" '$t'"))
println()
})
}
Movie titles grouped by month of release
Movies released in JUNE: 'Conan' 'Predator' 'Total Recall’
Movies released in OCTOBER: 'Terminator' 'Commando’
Movies released in JULY: 'Terminator 2'
Improved Collections
Inheritance is frequently overused in OO
• In particular the anti-pattern of ‘implementation inheritance’
• Were we inherit from a type solely to reuse its functionality
Export Clauses provide a much better alternative
• They make it easy for one type to wrap up another
• Whilst selectively exposing its functionality
Export Clauses
class MyBuffer {
val sb = new StringBuffer()
export sb.append
export sb.{ insert => putIn }
override def toString() = sb.toString()
}
def exportClauses() = {
val buffer = new MyBuffer()
buffer.append("Foo")
buffer.append("Bar")
buffer.append("Zed")
buffer.putIn(3, "Wibble")
buffer.putIn(12,"Wobble")
println(buffer)
}
FooWibbleBarWobbleZed
Export Clauses
Scala 3 allows Traits to have parameters
Trait Parameters
trait PricingEngine(val minPurchases: Int) {
def calcDiscount(purchases: List[String]) : Double
}
class MyPricingEngine extends PricingEngine(3) {
override def calcDiscount(purchases: List[String]) = {
if purchases.length >= minPurchases then 100.0 else 0.0
}
}
def traitParameters() = {
val pe = new MyPricingEngine()
println(pe.calcDiscount(List("AB12","CD34")))
println(pe.calcDiscount(List("AB12","CD34","EF56")))
}
0.0
100.0
Trait Parameters
Scala’s implicits let you abstract over context
• They are a great way to perform DI and implement Type Classes
However when incorrectly used they are a ‘chainsaw feature’
• You lose control over what the compiler is injecting on your behalf
In version 3 implicits are replaced with:
• Given instances
• Using classes
• Given imports
• Implicit conversions
Implicits Are Replaced
trait MakeImportant[T] {
def escalate(thing: T): T
}
given stringMakeImportant as MakeImportant[String] {
def escalate(thing: String) = thing.toUpperCase()
}
given intMakeImportant as MakeImportant[Int] {
def escalate(thing: Int) = thing * 100
}
Implicits Are Replaced
def doImportantWork[T](thing: T)(using imp: MakeImportant[T]) = {
print("Doing important work with: ")
println(imp.escalate(thing))
}
def givenInstances() = {
doImportantWork("wibble")
doImportantWork(123)
}
Doing important work with: WIBBLE
Doing important work with: 12300
Implicits Are Replaced
Scala 3 provides a new library for metaprogramming
• Replacing earlier attempts to add macros to the language
An inline keyword expands function calls at the point of use
• Unlike other languages the instruction to inline is a command
Quotation converts code into typed syntax trees
• Using a dedicated API and the new TASTy representation
• The syntax is ‘{…} for expressions and ‘[…] for types
Spicing converts an AST back into code
• The syntax is ${…}
Metaprogramming
package macros
import scala.quoted._
def test1()(using QuoteContext) = {
val expr = '{ 100 + 50 }
println("Evaluating Macro")
println("Type is: " + expr)
expr
}
inline def test2() = ${ test1() }
Metaprogramming
@main def foobar(): Unit = {
...
}
def usingMacros() = {
println("Using macros")
println(test2())
}
Evaluating Macro
Type is: Expr(<tasty tree>)
[info] running foobar
Pick an option:
0) Exit
1) Creator applications
...
12) Using macros
14) Collections
15) Quiz question
12
Using macros
150
Metaprogramming
The hand that wields
the knife shall never
wear the crown.
Gavin Esler

More Related Content

What's hot

ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021Jorge Vásquez
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
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
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmerGirish Kumar A L
 
Dive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through javaDive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through javaDamith Warnakulasuriya
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languagePawel Szulc
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
 

What's hot (19)

Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
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
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Dive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through javaDive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through java
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
 

Similar to The Great Scala Makeover

Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
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
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
 
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
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
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
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsRasan Samarasinghe
 

Similar to The Great Scala Makeover (20)

Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
(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?
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
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 @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
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
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 

More from Garth Gilmour

Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSGarth Gilmour
 
Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your VegGarth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresGarth Gilmour
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITGarth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Garth Gilmour
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in SpaceGarth Gilmour
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?Garth Gilmour
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlyGarth Gilmour
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinGarth Gilmour
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Garth Gilmour
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse RaceGarth Gilmour
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming Garth Gilmour
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopGarth Gilmour
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn FamilyGarth Gilmour
 
The Philosophy of DDD
The Philosophy of DDDThe Philosophy of DDD
The Philosophy of DDDGarth Gilmour
 

More from Garth Gilmour (20)

Compose in Theory
Compose in TheoryCompose in Theory
Compose in Theory
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJS
 
Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your Veg
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS Adventures
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise IT
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving Distantly
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into Kotlin
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse Race
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters Workshop
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn Family
 
The Philosophy of DDD
The Philosophy of DDDThe Philosophy of DDD
The Philosophy of DDD
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 

The Great Scala Makeover

  • 1. training@instil.co © Instil Software 2020 The Great Scala Makeover @GarthGilmour https://bitbucket.org/GarthGilmour/scala3-bash-feb2020
  • 2. Me
  • 4. Scala – The Early Days
  • 5. Scala – The Early Days
  • 6. Scala – The Early Days
  • 8. Dotty is the codename for the new Scala compiler • It has been rewritten from scratch for speed and correctness The language has been simplified and extended for Dotty • Unpopular and redundant features have been removed • New features reflect the increasing importance of FP • Implicits and macros remain, but in a new way Enter Dotty
  • 9. There is a new intermediate format • Your Scala 3 code compiles into TASTy • Short for Typed Abstract Syntax Trees • We then generate JS, Bytecode etc.. You can reflect on TASTY Syntax Trees • This is how macros are implemented Enter Dotty
  • 10. How To Try Out Scala 3 brew install sbt brew install lampepfl/brew/dotty Install VS Code and add to PATH • https://code.visualstudio.com/docs/setup/mac#_command-line sbt new lampepfl/dotty.g8 • Enter the info the wizard requires Change directory into project folder sbt launchIDE
  • 11. How To Try Out Scala 3
  • 12. Name Notes XML Literals Believe it or not this was once a great idea Delayed Init This partially breaks the ‘App’ class Procedure Syntax Writing ‘def foo() { … }’ no longer declares a return type of Unit The Do While Loop What? Existential Types Class Shadowing Symbol Literals Auto Application Weak Conformance Compound Types Auto Tupling [this] Qualifier Stuff That Dies
  • 13. def fakingDoWhile() = { println("Output from first weird loop...") while({ val x = Math.random() println(s"t$x") x > 0.5 })() println("Output from second weird loop...") while { val x = Math.random() println(s"t$x") x > 0.5 } do () } Output from first weird loop... 0.6506029560584671 0.4481933779924502 Output from second weird loop... 0.9451875748422434 0.5031857996404466 0.5923768910372654 0.8600801357886065 0.536180700764455 0.7337064700795435 0.7930386780841578 0.2882381886829134 No Do…While Loops
  • 14. Anything can be declared at the top level • Including Types, Variables and Functions • You no longer need package objects Any function can be main • By annotating with with ‘@main’ Top Level Declarations
  • 15. val menu = ""” Pick an option: 1) Creator applications 2) Extension methods 3) Basic enumerations 4) Enumerations as ADTs """ @main def foobar(): Unit = { var notDone = true while(notDone) { println(menu) val choice = scala.io.StdIn.readInt() choice match { case 1 => creatorApplications() case 2 => extensionMethods() case _ => notDone = false } } } Pick an option: 1) Creator applications 2) Extension methods 3) Basic enumerations 4) Enumerations as ADTs 1 Jane aged 25 Dave aged 27 Top Level Declarations
  • 16. package foo def *() = println("Hello dere...") Hello dere... A Fun Obfuscation package bar import foo.* @main def bar() = *()
  • 17. You could always avoid ‘new’ in Scala via an ‘apply’ method • But it would be laborious to do this for every type in your model Scala 3 makes it trivial to avoid new in almost all cases This is done by adding a fourth way of interpreting a function: This is referred to as ‘Creator Applications’ Creator Applications [Given f(args)] if f is syntactically a stable identifier, and new f where f is interpreted as a type identifier is applicable to args, continue with new f(args)
  • 18. class Person(name: String, age: Int) { def this(name: String) = this(name, 27) override def toString() = s"$name aged $age" } def creatorApplications() = { val p1 = Person("Jane", 25) val p2 = Person("Dave") println(p1) println(p2) } Jane aged 25 Dave aged 27 Creator Applications
  • 19. Scala 3 supports extensions to existing types • Useful when you don’t have the source or don’t want to modify it Extension methods can be defined singly or in groups • The latter is referred to as a collective extension Extensions can be operators and can be applied to generic types Extension Methods
  • 20. def (s: String).times2() = s + s extension on (s: String) { def times3() = s + s + s def times4() = s + s + s + s } def extensionMethods() = { val s1 = "Wibble" println(s1.times2()) println(s1.times3()) println(s1.times4()) } WibbleWibble WibbleWibbleWibble WibbleWibbleWibbleWibble Extension Methods
  • 21. Scala finally does Enums! • These were not available previously • The idea was to use Case Classes You can extend ‘java.lang.Enum’ • For interoperability with Java Enums can have type parameters • Giving you an easy way to do ADTs Enumerations J
  • 22. enum Direction { case NORTH, SOUTH, EAST, WEST def printArrow() = { var arrow = '?’ this match { case WEST => arrow = 0x2190 case EAST => arrow = 0x2192 case NORTH => arrow = 0x2191 case SOUTH => arrow = 0x2193 } println(arrow) } } def basicEnumerations() = { val d = Direction.NORTH print(d) d.printArrow() } NORTH↑ Enumerations J
  • 23. Does Anything About This Feel Familiar?
  • 24.
  • 25. Scala Verses Kotlin “There’s something I ought to tell you” “Tell me” “I don’t use the new keyword either” “I don’t use implicits either” “I also have enumerated types” “I also have extension methods” “I can declare top level types” Vs
  • 26. The new enumeration syntax makes it easy to create ADT’s • As in particular generic ADT’s like Option, Try and Either You could always do this with Case Classes • But the process is simplified to reflect their increasing relevance Enumerations as ADTs
  • 27. enum Try[+T] { case Success(val result: T) extends Try[T] case Failure(val error: String) extends Try[Nothing] def fold(errorHandler: String => Unit, resultHandler: T => Unit) = { this match { case Success(result) => resultHandler(result) case Failure(error) => errorHandler(error) } } } def readPropertyAsInt(name: String): Try[Int] = { val propertyValue = System.getProperty(name) try { Try.Success(Integer.parseInt(propertyValue)) } catch { case ex: NumberFormatException => Try.Failure(ex.getMessage) } } Enumerations as ADTs
  • 28. def enumerationsAsADTs() = { System.setProperty("testProp", "123") val result1 = readPropertyAsInt("testProp") val result2 = readPropertyAsInt("java.vendor") result1.fold( msg => println(s"Whoops - $msg"), num => println(s"Hurrah - $num") ) result2.fold( msg => println(s"Whoops - $msg"), num => println(s"Hurrah - $num") ) } Hurrah - 123 Whoops - For input string: "AdoptOpenJDK" Enumerations as ADTs
  • 29. Scala 3 adds support for: • Union Types • Intersection Types • Literal Types • Opaque Type Aliases This gives a richer toolkit for describing data • Fans of DDD should be very happy New Ways To Manipulate Types
  • 30. Parameters in Scala 3 can be defined as unions of types • Where the types don’t have to share a common base class For example ‘def foo(input: Foo | Bar | Zed)’ This will also work with literals Union Types
  • 31. case class WorkExperience(val years: Int) case class Degree(val subject: String) case class Publication(val isbn: String) def employ(name: String, reason: Degree | WorkExperience | Publication) = { print(s"Employing $name because of ") reason match { case Degree(subject) => println(s"their degree in $subject") case WorkExperience(years) => println(s"their $years years experience") case Publication(_) => println("they wrote a book") } } Union Types
  • 32. employ("Dave", Degree("Physics")) employ("Jane", WorkExperience(10)) employ("Fred", Publication("ABC-123")) Employing Dave because of their degree in Physics Employing Jane because of their 10 years experience Employing Fred because of they wrote a book Union Types
  • 33. Parameters can also be the intersection of multiple types • Where a type must extend multiple traits For example ‘def foo(input: Foo & Bar & Zed)’ Intersection Types
  • 34. trait Edible { def eat(): Unit } trait Drinkable { def drink(): Unit } class Apple extends Edible { override def eat() = println("Eating an Apple") } class Milk extends Drinkable { override def drink() = println("Drinking some Milk") } class Soup extends Edible with Drinkable { override def eat() = println("Eating Soup") override def drink() = println("Drinking Soup") } Intersection Types
  • 35. def intersectionTypes() = { def eatDrinkAndBeMerry(input: Edible & Drinkable) = { input.eat() input.drink() } //eatDrinkAndBeMerry(Apple()) //Will not compile //eatDrinkAndBeMerry(Milk()) //Will not compile eatDrinkAndBeMerry(Soup()) } Eating Soup Drinking Soup Intersection Types
  • 36. Literal Types started in Dotty but were backported to 2.13 • They allow you to treat any literal value as a type in its own right • 1, 2.3, “ABC” can all be used as types with a singleton instance These are especially powerful when combined with Union Types • E.g. the input to a method can be constrained to the names of events Literal Types
  • 37. def literalTypes() = { def specialFunction(input: "abc" | "def" | "ghi") = println(input) val specialNumber: 123 = 123 val specialOption: Option[456] = Option(456) specialFunction("def") specialFunction("ghi") //specialFunction("xyz") //Will not compile println(specialNumber) println(specialOption.getOrElse(0)) } def ghi 123 456 Literal Types
  • 38. Opaque type aliases provide abstraction without overhead Let’s say you want to have an ‘ItemID’ type • Which can be expressed as a regular String You are concerned about erroneous conversions • E.g. ‘addItem(“Toaster”)’ instead of ‘addItem(“AB12”)’ One option would be to create a wrapper type • An ‘ItemID’ class with a single field of type String • But this would introduce the overhead of (un)boxing Type aliases provide a neat solution Opaque Type Aliases
  • 39. package demo import scala.collection.mutable.Stack opaque type ItemID = String object ItemID { def apply(str: String): ItemID = str } class Shop { val purchases = Stack[ItemID]() def buy(item: ItemID) = purchases.push(item) override def toString() = purchases.toString() } Opaque Type Aliases
  • 40. import demo.Shop import demo.ItemID def opaqueTypeAliases() = { val shop = new Shop() //shop.buy("AB12") //Will Not Compile val item1: ItemID = ItemID("AB12") shop.buy(item1) shop.buy(ItemID("CD34")) shop.buy(ItemID("EF56")) println(shop) } Stack(EF56, CD34, AB12) Opaque Type Aliases
  • 41. Does Anything About This Feel Familiar?
  • 42. Does Anything About This Feel Familiar?
  • 43. Scala Verses F# “There’s something I ought to tell you” “Tell me” “I don’t need wrapper types either” “I also support union types” Vs
  • 44. Significant Whitespace This one was a shock • …and it is still taking a while to percolate Scala 3 supports significant whitespace • If you omit the parenthesis at the start of a function then whitespace is used instead • All the conditionals and loops have a new form that does not need parenthesis
  • 45. @main def foobar(): Unit = var notDone = true while notDone do println(menu) val choice = scala.io.StdIn.readInt() choice match case 1 => creatorApplications() case 2 => extensionMethods() case _ => notDone = false Significant Whitespace @main def foobar(): Unit = { var notDone = true while(notDone) { println(menu) val choice = scala.io.StdIn.readInt() choice match { case 1 => creatorApplications() case 2 => extensionMethods() case _ => notDone = false } } }
  • 46. Does Anything About This Feel Familiar?
  • 47. Scala Verses Python “There’s something I ought to tell you” “Tell me” “I don’t use braces either” Vs
  • 48. Collections have always been a strong point for Scala • Despite complaints that they are too pure or should be purer J There were improvements in 2.13 which are continued into to 3.0 • New methods have been added and the implementation is simplified Improved Collections
  • 49. enum Rating { case GREAT, BRILLIANT, SUPERB, LIFE_CHANGING } class Movie(val title: String, val rating: Rating, val releaseDate: LocalDate, val quotes: List[String]) def greatActionMovies(): List[Movie] = List( Movie("Predator", Rating.LIFE_CHANGING, of(1987, JUNE, 12), List("Get to the Chopper!", "Stick around.", "If it bleeds, we can kill it.", "He's using the trees.", "We move, five meter spread, no sound.")), Movie(...), Improved Collections
  • 50. def triplesOfQuotes(title: String) = { val movies = greatActionMovies() println(s"All possible triples of $title quotes") movies.find(_.title == title) .map(m => m.quotes.combinations(3)) .fold(println("Not found!"))(_.foreach(println)) } triplesOfQuotes("Commando") All possible triples of Commando quotes List(I have to remind you Sully, this is my weak arm!, I eat Green Berets for breakfast. And right now, I'm very hungry!, Don't disturb my friend, he's dead tired.) List(...) List(...) List(...) List(...) Improved Collections
  • 51. def movieTitlesByMonthReleased() = { val movies = greatActionMovies() println("Movie titles grouped by month of release") movies.groupMap(_.releaseDate.getMonth)(_.title) .foreach(row => { val(month, titles) = row print(s"tMovies released in $month: ") titles.foreach(t => print(s" '$t'")) println() }) } Movie titles grouped by month of release Movies released in JUNE: 'Conan' 'Predator' 'Total Recall’ Movies released in OCTOBER: 'Terminator' 'Commando’ Movies released in JULY: 'Terminator 2' Improved Collections
  • 52. Inheritance is frequently overused in OO • In particular the anti-pattern of ‘implementation inheritance’ • Were we inherit from a type solely to reuse its functionality Export Clauses provide a much better alternative • They make it easy for one type to wrap up another • Whilst selectively exposing its functionality Export Clauses
  • 53. class MyBuffer { val sb = new StringBuffer() export sb.append export sb.{ insert => putIn } override def toString() = sb.toString() } def exportClauses() = { val buffer = new MyBuffer() buffer.append("Foo") buffer.append("Bar") buffer.append("Zed") buffer.putIn(3, "Wibble") buffer.putIn(12,"Wobble") println(buffer) } FooWibbleBarWobbleZed Export Clauses
  • 54. Scala 3 allows Traits to have parameters Trait Parameters
  • 55. trait PricingEngine(val minPurchases: Int) { def calcDiscount(purchases: List[String]) : Double } class MyPricingEngine extends PricingEngine(3) { override def calcDiscount(purchases: List[String]) = { if purchases.length >= minPurchases then 100.0 else 0.0 } } def traitParameters() = { val pe = new MyPricingEngine() println(pe.calcDiscount(List("AB12","CD34"))) println(pe.calcDiscount(List("AB12","CD34","EF56"))) } 0.0 100.0 Trait Parameters
  • 56. Scala’s implicits let you abstract over context • They are a great way to perform DI and implement Type Classes However when incorrectly used they are a ‘chainsaw feature’ • You lose control over what the compiler is injecting on your behalf In version 3 implicits are replaced with: • Given instances • Using classes • Given imports • Implicit conversions Implicits Are Replaced
  • 57. trait MakeImportant[T] { def escalate(thing: T): T } given stringMakeImportant as MakeImportant[String] { def escalate(thing: String) = thing.toUpperCase() } given intMakeImportant as MakeImportant[Int] { def escalate(thing: Int) = thing * 100 } Implicits Are Replaced
  • 58. def doImportantWork[T](thing: T)(using imp: MakeImportant[T]) = { print("Doing important work with: ") println(imp.escalate(thing)) } def givenInstances() = { doImportantWork("wibble") doImportantWork(123) } Doing important work with: WIBBLE Doing important work with: 12300 Implicits Are Replaced
  • 59. Scala 3 provides a new library for metaprogramming • Replacing earlier attempts to add macros to the language An inline keyword expands function calls at the point of use • Unlike other languages the instruction to inline is a command Quotation converts code into typed syntax trees • Using a dedicated API and the new TASTy representation • The syntax is ‘{…} for expressions and ‘[…] for types Spicing converts an AST back into code • The syntax is ${…} Metaprogramming
  • 60. package macros import scala.quoted._ def test1()(using QuoteContext) = { val expr = '{ 100 + 50 } println("Evaluating Macro") println("Type is: " + expr) expr } inline def test2() = ${ test1() } Metaprogramming
  • 61. @main def foobar(): Unit = { ... } def usingMacros() = { println("Using macros") println(test2()) } Evaluating Macro Type is: Expr(<tasty tree>) [info] running foobar Pick an option: 0) Exit 1) Creator applications ... 12) Using macros 14) Collections 15) Quiz question 12 Using macros 150 Metaprogramming
  • 62.
  • 63. The hand that wields the knife shall never wear the crown. Gavin Esler