SlideShare a Scribd company logo
Scala: few simple type
tricks for mortals
Ruslan Shevchenko
<ruslan@shevchenko.kiev.ua>
Hieronymus Bosch
“A visual guide to the Scala language” oil on oak panels, 1490-1510
// http://classicprogrammerpaintings.tumblr.com/
scala types
Structured
Classical OO
Algebraic
Generic
Aliasing
5D SPACE
Alternatives
• Classical OO / Algebraic (case classes)
• Generic / Type Alias
• Structured / Nominal
// decrease problem space
Alternatives
• Prefer specific style
• (typelevel: prefer Generic + ADT)
• (java++ : prefer OO + std. ADT)
• Try to set some rules.
• http://www.lihaoyi.com/post/StrategicScalaStylePrincipleofLeastPower.html
• least power
• most readability
Alternatives
• Classical OO / ADT
• state vs functionality.
OO: Object = State + Function
FP:
State = ADT, passive.
Object = Service over State
Non-ADT Object with state ?
rare, special, ….
Alternatives
• Generic/Type Alias
case class User[IdType,Address](
id: IdType,
firstName: String.
lastName: String
address: Address
)
case class User extends IdEntity(
id: IdType,
firstName: String,
lastName: String,
address: Address
) {
type Address = …..
)
Type Aliases are path-depended
val a = retrieveUser(“a1”)
val b = retrieveUser(“b1”)
a.address and b.address - different types
Aux pattern
object User
{
type Aux[I,A] = User {
type IdType = I
type Address = A
}
}
def method[Id,Type](user: User.Aux[Id,Type] ): X =
…………..
// original from shapeless
When to prefer generic ?
• Containers.
• Compositions.
• Internal machinery.
• (part of more complex process)
• Dotty: unification of type aliases and type
parameters.
{compile/run}-time dispatch
• run time dispatch — via java virtual dispatch
• depends from one object
• final object type can not be known at compile-time
• compile time dispatch — via implicit resolution
• depends from multiple objects
• final object types must be known at compile-time
{compile/run}-time dispatch
• run time dispatch — via java virtual dispatch
• depends from one object
• final object type can not be known at compile-time
• compile time dispatch — via implicit resolution
• depends from multiple objects
• final object types must be known at compile-time
Immutable data —> we know constructor
implicit resolution
• provide global rule in you world
• rule must be really global or special for you types
• good citizent in big project must be tolerant:
• do not force others to know something about you
implicits
• keep you implicits in your scope [companion obj, etc]
• problem: we want to have different behaviour for
different object state (known at compile time)
tagged typesobject tagged types {
trait Tagged[+V]
type @@[V,T] = V with Tagged[T]
implicit class WithTag[V](val v:V) extends AnyVal
{
def @@[T](t:T) = v.asInstanceOf[T]
def tag[T] = v.asInstanceOf[T]
}
}
// origin: was as scalaz, shapeless
tagged typesobject tagged types {
trait Tagged[+V]
type @@[V,T] = V with Tagged[T]
implicit class WithTag[V](val v:V) extends AnyVal
{
def @@[T](t:T) = v.asInstanceOf[T]
def tag[T] = v.asInstanceOf[T]
}
}
// origin: was as scalaz, shapeless
sealed trait UserLifecycle
trait New extends UserLifecycle
trait Existing extends UserLifecycle
case class User(….)
tagged typesobject tagged types {
trait Tagged[+V]
type @@[V,T] = V with Tagged[T]
implicit class WithTag[V](val v:V) extends AnyVal
{
def @@[T](t:T) = v.asInstanceOf[T]
def tag[T] = v.asInstanceOf[T]
}
}
// origin: was as scalaz, shapeless
case class Msg(v:String)
object User {
implicit def msgNew(u: User @@New:Msg = Msg(“Hi”)
implicit def msgExisting(u: User@@Existing):Msg = Msg(“Hi again!”)
}
sealed trait UserLifecycle
trait New extends UserLifecycle
trait Existing extends UserLifecycle
tagged typesobject tagged types {
trait Tagged[+V]
type @@[V,T] = V with Tagged[T]
implicit class WithTag[V](val v:V) extends AnyVal
{
def @@[T](t:T) = v.asInstanceOf[T]
def tag[T] = v.asInstanceOf[T]
}
}
// see: refinement
case class Msg(v:String)
object User {
implicit def msgNew(u: User @@New:Msg = Msg(“Hi”)
implicit def msgExisting(u: User@@Existing):Msg = Msg(“Hi again!”)
}
sealed trait UserLifecycle
trait New extends UserLifecycle
trait Existing extends UserLifecycle
class UserService
{
def create(cn: Info): User @@ New
def meet(u: User @@ New): User @@ Existing
}
val u = userService.create(cn)
printMsg(u)
> >> “Hi”
val u1 = userService.meet(u)
printMsg(u1)
>>> “Hi again!”
implicit evidence
• existing implicit evidence <=> existence of
property
object example {
def notCallMeWithA[T](t:T)(implicit evidence: Not[A,T])
trait Not[A,T]
implicit def n1[A,B](implicit evidence A <:< B) = Not.instance
implicit def n2[A,B](implicit evidence B <:< A) = Not.instance
implicit def n3[A] = Not.instance
}
type arithmetics
trait Nat {
type Current <: Nat
type Next <: Nat
}
type Zero {
type Current = Zero
type Next = Succ(Zero)
}
type Succ[X<:Nat]
{
type Current = Succ[X]
type Next = Succ[Succ[X]]
}
type _0 = Zero
type _1 = Succ[Zero]
type _2 = Succ[Succ[Zero]]
totally ineffective
shapeless contains effective implementation
class SizedList[X <: Nat]
{
……
}
Resources:
• shapeless (big, use with care)
• https://github.com/milessabin/shapeless
• http://mpilquist.github.io/blog/2015/04/22/intro-to-shapeless/
• type-level computations
• http://slick.typesafe.com/talks/scalaio2014/Type-Level_Computations.pdf
Questions ?
• Thanks for attention.

More Related Content

What's hot

A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
Debasish Ghosh
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
AnsviaLab
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda Days
Konrad Malawski
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Peter Maas
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
Derek Chen-Becker
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
Bert Van Vreckem
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
Tomer Gabel
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
Razvan Cojocaru
 
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
IndicThreads
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 

What's hot (20)

A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda Days
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
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
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
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
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 

Similar to Few simple-type-tricks in scala

Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
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
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
About Python
About PythonAbout Python
About Python
Shao-Chuan Wang
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Rahul Jain
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
mircodotta
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
Sep 15
Sep 15Sep 15
Sep 15
dilipseervi
 
Sep 15
Sep 15Sep 15
Sep 15
Zia Akbar
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
RAMU KOLLI
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
Khaled Anaqwa
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
VijalJain3
 

Similar to Few simple-type-tricks in scala (20)

Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
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
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
About Python
About PythonAbout Python
About Python
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
Sep 15
Sep 15Sep 15
Sep 15
 
Sep 15
Sep 15Sep 15
Sep 15
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 

More from Ruslan Shevchenko

Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Ruslan Shevchenko
 
Svitla talks 2021_03_25
Svitla talks 2021_03_25Svitla talks 2021_03_25
Svitla talks 2021_03_25
Ruslan Shevchenko
 
Akka / Lts behavior
Akka / Lts behaviorAkka / Lts behavior
Akka / Lts behavior
Ruslan Shevchenko
 
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
Papers We Love / Kyiv :  PAXOS (and little about other consensuses )Papers We Love / Kyiv :  PAXOS (and little about other consensuses )
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
Ruslan Shevchenko
 
Scala / Technology evolution
Scala  / Technology evolutionScala  / Technology evolution
Scala / Technology evolution
Ruslan Shevchenko
 
{co/contr} variance from LSP
{co/contr} variance  from LSP{co/contr} variance  from LSP
{co/contr} variance from LSP
Ruslan Shevchenko
 
N flavors of streaming
N flavors of streamingN flavors of streaming
N flavors of streaming
Ruslan Shevchenko
 
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Ruslan Shevchenko
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
Ruslan Shevchenko
 
Java & low latency applications
Java & low latency applicationsJava & low latency applications
Java & low latency applications
Ruslan Shevchenko
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
Ruslan Shevchenko
 
IDLs
IDLsIDLs
R ext world/ useR! Kiev
R ext world/ useR!  KievR ext world/ useR!  Kiev
R ext world/ useR! Kiev
Ruslan Shevchenko
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platform
Ruslan Shevchenko
 
Behind OOD: domain modelling in post-OO world.
Behind OOD:  domain modelling in post-OO world.Behind OOD:  domain modelling in post-OO world.
Behind OOD: domain modelling in post-OO world.
Ruslan Shevchenko
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
Ruslan Shevchenko
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N years
Ruslan Shevchenko
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Ruslan Shevchenko
 
Ruslan.shevchenko: most functional-day-kiev 2014
Ruslan.shevchenko: most functional-day-kiev 2014Ruslan.shevchenko: most functional-day-kiev 2014
Ruslan.shevchenko: most functional-day-kiev 2014
Ruslan Shevchenko
 
Web architecture - overview of techniques.
Web architecture - overview of  techniques.Web architecture - overview of  techniques.
Web architecture - overview of techniques.
Ruslan Shevchenko
 

More from Ruslan Shevchenko (20)

Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
 
Svitla talks 2021_03_25
Svitla talks 2021_03_25Svitla talks 2021_03_25
Svitla talks 2021_03_25
 
Akka / Lts behavior
Akka / Lts behaviorAkka / Lts behavior
Akka / Lts behavior
 
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
Papers We Love / Kyiv :  PAXOS (and little about other consensuses )Papers We Love / Kyiv :  PAXOS (and little about other consensuses )
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
 
Scala / Technology evolution
Scala  / Technology evolutionScala  / Technology evolution
Scala / Technology evolution
 
{co/contr} variance from LSP
{co/contr} variance  from LSP{co/contr} variance  from LSP
{co/contr} variance from LSP
 
N flavors of streaming
N flavors of streamingN flavors of streaming
N flavors of streaming
 
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
Java & low latency applications
Java & low latency applicationsJava & low latency applications
Java & low latency applications
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
 
IDLs
IDLsIDLs
IDLs
 
R ext world/ useR! Kiev
R ext world/ useR!  KievR ext world/ useR!  Kiev
R ext world/ useR! Kiev
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platform
 
Behind OOD: domain modelling in post-OO world.
Behind OOD:  domain modelling in post-OO world.Behind OOD:  domain modelling in post-OO world.
Behind OOD: domain modelling in post-OO world.
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N years
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Ruslan.shevchenko: most functional-day-kiev 2014
Ruslan.shevchenko: most functional-day-kiev 2014Ruslan.shevchenko: most functional-day-kiev 2014
Ruslan.shevchenko: most functional-day-kiev 2014
 
Web architecture - overview of techniques.
Web architecture - overview of  techniques.Web architecture - overview of  techniques.
Web architecture - overview of techniques.
 

Recently uploaded

原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
Ayan Halder
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 

Recently uploaded (20)

原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 

Few simple-type-tricks in scala

  • 1. Scala: few simple type tricks for mortals Ruslan Shevchenko <ruslan@shevchenko.kiev.ua>
  • 2. Hieronymus Bosch “A visual guide to the Scala language” oil on oak panels, 1490-1510 // http://classicprogrammerpaintings.tumblr.com/
  • 4. Alternatives • Classical OO / Algebraic (case classes) • Generic / Type Alias • Structured / Nominal // decrease problem space
  • 5. Alternatives • Prefer specific style • (typelevel: prefer Generic + ADT) • (java++ : prefer OO + std. ADT) • Try to set some rules. • http://www.lihaoyi.com/post/StrategicScalaStylePrincipleofLeastPower.html • least power • most readability
  • 6. Alternatives • Classical OO / ADT • state vs functionality. OO: Object = State + Function FP: State = ADT, passive. Object = Service over State Non-ADT Object with state ? rare, special, ….
  • 7. Alternatives • Generic/Type Alias case class User[IdType,Address]( id: IdType, firstName: String. lastName: String address: Address ) case class User extends IdEntity( id: IdType, firstName: String, lastName: String, address: Address ) { type Address = ….. )
  • 8. Type Aliases are path-depended val a = retrieveUser(“a1”) val b = retrieveUser(“b1”) a.address and b.address - different types Aux pattern object User { type Aux[I,A] = User { type IdType = I type Address = A } } def method[Id,Type](user: User.Aux[Id,Type] ): X = ………….. // original from shapeless
  • 9. When to prefer generic ? • Containers. • Compositions. • Internal machinery. • (part of more complex process) • Dotty: unification of type aliases and type parameters.
  • 10. {compile/run}-time dispatch • run time dispatch — via java virtual dispatch • depends from one object • final object type can not be known at compile-time • compile time dispatch — via implicit resolution • depends from multiple objects • final object types must be known at compile-time
  • 11. {compile/run}-time dispatch • run time dispatch — via java virtual dispatch • depends from one object • final object type can not be known at compile-time • compile time dispatch — via implicit resolution • depends from multiple objects • final object types must be known at compile-time Immutable data —> we know constructor
  • 12. implicit resolution • provide global rule in you world • rule must be really global or special for you types • good citizent in big project must be tolerant: • do not force others to know something about you implicits • keep you implicits in your scope [companion obj, etc] • problem: we want to have different behaviour for different object state (known at compile time)
  • 13. tagged typesobject tagged types { trait Tagged[+V] type @@[V,T] = V with Tagged[T] implicit class WithTag[V](val v:V) extends AnyVal { def @@[T](t:T) = v.asInstanceOf[T] def tag[T] = v.asInstanceOf[T] } } // origin: was as scalaz, shapeless
  • 14. tagged typesobject tagged types { trait Tagged[+V] type @@[V,T] = V with Tagged[T] implicit class WithTag[V](val v:V) extends AnyVal { def @@[T](t:T) = v.asInstanceOf[T] def tag[T] = v.asInstanceOf[T] } } // origin: was as scalaz, shapeless sealed trait UserLifecycle trait New extends UserLifecycle trait Existing extends UserLifecycle case class User(….)
  • 15. tagged typesobject tagged types { trait Tagged[+V] type @@[V,T] = V with Tagged[T] implicit class WithTag[V](val v:V) extends AnyVal { def @@[T](t:T) = v.asInstanceOf[T] def tag[T] = v.asInstanceOf[T] } } // origin: was as scalaz, shapeless case class Msg(v:String) object User { implicit def msgNew(u: User @@New:Msg = Msg(“Hi”) implicit def msgExisting(u: User@@Existing):Msg = Msg(“Hi again!”) } sealed trait UserLifecycle trait New extends UserLifecycle trait Existing extends UserLifecycle
  • 16. tagged typesobject tagged types { trait Tagged[+V] type @@[V,T] = V with Tagged[T] implicit class WithTag[V](val v:V) extends AnyVal { def @@[T](t:T) = v.asInstanceOf[T] def tag[T] = v.asInstanceOf[T] } } // see: refinement case class Msg(v:String) object User { implicit def msgNew(u: User @@New:Msg = Msg(“Hi”) implicit def msgExisting(u: User@@Existing):Msg = Msg(“Hi again!”) } sealed trait UserLifecycle trait New extends UserLifecycle trait Existing extends UserLifecycle class UserService { def create(cn: Info): User @@ New def meet(u: User @@ New): User @@ Existing } val u = userService.create(cn) printMsg(u) > >> “Hi” val u1 = userService.meet(u) printMsg(u1) >>> “Hi again!”
  • 17. implicit evidence • existing implicit evidence <=> existence of property object example { def notCallMeWithA[T](t:T)(implicit evidence: Not[A,T]) trait Not[A,T] implicit def n1[A,B](implicit evidence A <:< B) = Not.instance implicit def n2[A,B](implicit evidence B <:< A) = Not.instance implicit def n3[A] = Not.instance }
  • 18. type arithmetics trait Nat { type Current <: Nat type Next <: Nat } type Zero { type Current = Zero type Next = Succ(Zero) } type Succ[X<:Nat] { type Current = Succ[X] type Next = Succ[Succ[X]] } type _0 = Zero type _1 = Succ[Zero] type _2 = Succ[Succ[Zero]] totally ineffective shapeless contains effective implementation class SizedList[X <: Nat] { …… }
  • 19. Resources: • shapeless (big, use with care) • https://github.com/milessabin/shapeless • http://mpilquist.github.io/blog/2015/04/22/intro-to-shapeless/ • type-level computations • http://slick.typesafe.com/talks/scalaio2014/Type-Level_Computations.pdf
  • 20. Questions ? • Thanks for attention.