SlideShare uma empresa Scribd logo
1 de 47
“Insulin” for Scala’s
Syntactic Diabetes
Tzach Zohar // Kenshoo // Scalapeño 2016
OR:
How to adopt Scala and
survive
source
source
Who am I
NOT Chuck Norris!
Scala “Advanced Beginner” / “Competent”
System Architect @ Kenshoo
Who’s Kenshoo
10-year Tel-Aviv based startup
Industry Leader in Digital Marketing
Java + JavaScript shop
http://kenshoo.com/
Scala @ Kenshoo
5 services written in Scala
More to come...
Internal Scala course on the go
What’s so scary?
trait GeneralizedCategory {
type U <: Hom
type =>:[A >: U#L <: U#H, B >: U#L <: U#H] = U#C[A, B]
def id[A >: U#L <: U#H]: A =>: A
def compose[A >: U#L <: U#H, B >: U#L <: U#H, C >: U#L <: U#H](
f: B =>: C, g: A =>: B): A =>: C
def *[UY<:Hom](that : GeneralizedCategory {type U=UY}) =
Category.ProductCategory[U,UY](this,that)
}
source
source
source
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
Now for some sane examples
source
val tuples = List((1, 374), (3, 42), (5, 693))
val ids = tuples.map(_._1)
val ids = tuples.map(tuple => tuple._1)
val ids = tuples.map { tuple => tuple._1 }
val tuples = List((1, 374), (3, 42), (5, 693))
val ids = tuples.map(_._1)
val ids = tuples.map(tuple => tuple._1)
val ids = tuples.map { tuple => tuple._1 }
val ids = tuples.map(t => t match { case (id, value)=> id })
val ids = tuples.map(_ match { case (id, value) => id })
val ids = tuples.map({ case (id, value) => id })
val ids = tuples.map { case (id, value) => id }
val ids = tuples.map { case (id, _) => id }
case class Profile() { … }
case class ProfileId(id: Int)
def loadProfile(profileId: ProfileId): Profile = ???
case class Profile() { … }
case class ProfileId(id: Int)
def loadProfile(profileId: ProfileId): Profile = ???
loadProfile(ProfileId(3))
loadProfile(new ProfileId(3))
loadProfile(profileId = ProfileId(3))
loadProfile(profileId = new ProfileId(3))
case class Profile() { … }
case class ProfileId(id: Int)
implicit def toId(i :Int): ProfileId = ProfileId(i)
def loadProfile(profileId: ProfileId): Profile = ???
loadProfile(ProfileId(3))
loadProfile(new ProfileId(3))
loadProfile(profileId = ProfileId(3))
loadProfile(profileId = new ProfileId(3))
loadProfile(3)
loadProfile(profileId = 3)
def loadInt(): Int = { … }
def f(value: () => Int) = { … }
f(() => 2 + loadInt())
def loadInt(): Int = { … }
def f(value: () => Int) = { … }
f(() => 2 + loadInt())
def f(value: => Int) = { … }
f(2 + loadInt())
Too Much Sugar?
source
Issues so far
Too many ways to write the same thing
Tradeoff between short and readable
Advanced features getting in the way
Insulin to the rescue
1. Style Guides
source
Style Guides
1. The basic: Official Scala-Lang Style Guide
2. The conservative: Databricks' Scala Style Guide
3. The exhaustive: Twitter's Effective Scala
4. Your own!
Style Guides
implicit def toId(i :Int): ProfileId = ProfileId(i)
loadProfile(ProfileId(3))
loadProfile(3)
“Do not use implicits to do automatic
conversions between similar datatypes”
Style Guides
“Avoid infix notation for methods
that aren't symbolic methods”
list map func
string contains "foo"
list.map(func)
string.contains("foo")
val x = y + 2
Style Guides
val ids = tuples.map(t => t match { case (id, value)=> id })
val ids = tuples.map(_ match { case (id, value) => id })
val ids = tuples.map { case (id, value) => id }
val ids = tuples.map { case (id, _) => id }
“Use pattern matching directly in function
definitions whenever applicable”
Style Guides
def f(value: => Int) = ???
f(2 + 3)
def f(value: () => Int) = ???
f(() => 2 + 3)
“Avoid using call by name.
Use () => T explicitly”
@throws[IOException]
def mightThrowException(): Int
def neverThrowsException(): Option[Int]
def neverThrowsException(): Try[Int]
def neverThrowsException(): Either[Int, String]
def neverThrowsException(): MyResult
Style Guides
“Scala provides an exception facility, but do not
use it for commonplace errors”
val ids = tuples.map(_._1)
val ids = tuples.map(tuple => tuple._1)
val ids = tuples.map { case (id, value) => id }
val ids = tuples.map { case (id, _) => id }
Style Guides
“Avoid using tuple field names
like _1, prefer pattern matching or
a dedicated case class”
2. Code Reviews
source
Code Reviews
Refer author to Style Guides
Mix “Scala Levels” - juniors should review seniors’ code
Code Reviews
Code Reviews
Code Reviews
[Only] methods which act as
accessors [...] should be declared
without parentheses, except if they
have side effects
3. Style Checkers
source
Style Checkers
Automate some of the (simpler) rules
1. Scalastyle (SBT/Gradle/Maven/Eclipse/IntelliJ)
2. Scalafmt (SBT/Vim/CLI/IntelliJ) [NEW]
⌚ 18:45:25 ➜ sbt scalastyle
[info] Loading project definition from /.../project
[info] Set current project to myProject (in build file:/.../)
[warn] MyJob.scala:31:6: parameter.number.message
[error]MyService.scala:42:6: public.methods.have.type.message
[info] Processed 42 file(s)
[info] Found 1 errors
[info] Found 2 warnings
[info] Found 0 infos
[info] Finished in 39 ms
Style Checkers
4. Scala Levels
source
Scala Levels
Application Programmer Library Designer
A1: Beginner L1: Junior
A2: Intermediate L2: Senior
A3: Expert L3: Expert
Defined by Martin Odersky in a 2011 post
Scala Levels
Application Includes
A1: Beginner Basic syntax; Simple Closures;
Collections; For-expressions; …
A2: Intermediate Pattern matching; Trait composition;
(Tail) Recursion; …
A3: Expert Folds; Streams + other lazy data
structures; Actors; …
Scala Levels
Library Includes
L1: Junior Type parameters; Traits; Lazy vals;
Currying; By-name parameters
L2: Senior Variance; Existential types; Cake Pattern;
Structural types; Extractors; …
L3: Expert Early initializers; Abstract types; Implicit
definitions; Higher-kinded types; …
source
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
source
Conclusions
1. Intermediate Scala works
(might be better than Expert Java!)
2. Style and Feature-set can
be controlled
3. No Chuck-Norrisness Required
source
Thank You

Mais conteúdo relacionado

Mais procurados

Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
NLJUG
 

Mais procurados (20)

Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
 
Comparing Golang and understanding Java Value Types
Comparing Golang and understanding Java Value TypesComparing Golang and understanding Java Value Types
Comparing Golang and understanding Java Value Types
 
Scala’s implicits
Scala’s implicitsScala’s implicits
Scala’s implicits
 
Java principles
Java principlesJava principles
Java principles
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
 
Basic online java course - Brainsmartlabs
Basic online java course  - BrainsmartlabsBasic online java course  - Brainsmartlabs
Basic online java course - Brainsmartlabs
 
java token
java tokenjava token
java token
 
Lambdas
LambdasLambdas
Lambdas
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Java script unleashed
Java script unleashedJava script unleashed
Java script unleashed
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Learn To Code: Diving deep into java
Learn To Code: Diving deep into javaLearn To Code: Diving deep into java
Learn To Code: Diving deep into java
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Tech Talk - Things I Learned at Scala Days 2013
Tech Talk - Things I Learned at Scala Days 2013Tech Talk - Things I Learned at Scala Days 2013
Tech Talk - Things I Learned at Scala Days 2013
 
Applicative style programming
Applicative style programmingApplicative style programming
Applicative style programming
 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8
 

Destaque

A microservice approach for legacy modernisation
A microservice approach for legacy modernisationA microservice approach for legacy modernisation
A microservice approach for legacy modernisation
luisw19
 

Destaque (20)

Simple, battle proven microservices strategy
Simple, battle proven microservices strategySimple, battle proven microservices strategy
Simple, battle proven microservices strategy
 
Everyone's guide to event sourcing and async-messaging
Everyone's guide to event sourcing and async-messagingEveryone's guide to event sourcing and async-messaging
Everyone's guide to event sourcing and async-messaging
 
Everyone's Guide to States, Events and Async-Messaging for Microservices
Everyone's Guide to States, Events and Async-Messaging for MicroservicesEveryone's Guide to States, Events and Async-Messaging for Microservices
Everyone's Guide to States, Events and Async-Messaging for Microservices
 
Spark Your Legacy (Spark Summit 2016)
Spark Your Legacy (Spark Summit 2016)Spark Your Legacy (Spark Summit 2016)
Spark Your Legacy (Spark Summit 2016)
 
Coderetreat - What, Why and How
Coderetreat - What, Why and HowCoderetreat - What, Why and How
Coderetreat - What, Why and How
 
Microservices Tutorial Session at JavaOne 2016
Microservices Tutorial Session at JavaOne 2016Microservices Tutorial Session at JavaOne 2016
Microservices Tutorial Session at JavaOne 2016
 
Microservices in Java and Scala (sfscala)
Microservices in Java and Scala (sfscala)Microservices in Java and Scala (sfscala)
Microservices in Java and Scala (sfscala)
 
Enterprise APIs With Ease - Scala Developers of Barcelona
Enterprise APIs With Ease - Scala Developers of BarcelonaEnterprise APIs With Ease - Scala Developers of Barcelona
Enterprise APIs With Ease - Scala Developers of Barcelona
 
Why Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldWhy Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data World
 
A pattern language for microservices (#SFMicroservices)
A pattern language for microservices (#SFMicroservices)A pattern language for microservices (#SFMicroservices)
A pattern language for microservices (#SFMicroservices)
 
Events on the outside, on the inside and at the core (jfokus jfokus2016)
Events on the outside, on the inside and at the core (jfokus jfokus2016)Events on the outside, on the inside and at the core (jfokus jfokus2016)
Events on the outside, on the inside and at the core (jfokus jfokus2016)
 
A microservice approach for legacy modernisation
A microservice approach for legacy modernisationA microservice approach for legacy modernisation
A microservice approach for legacy modernisation
 
Microservices and Redis #redisconf Keynote
Microservices and Redis #redisconf KeynoteMicroservices and Redis #redisconf Keynote
Microservices and Redis #redisconf Keynote
 
Developing functional domain models with event sourcing (sbtb, sbtb2015)
Developing functional domain models with event sourcing (sbtb, sbtb2015)Developing functional domain models with event sourcing (sbtb, sbtb2015)
Developing functional domain models with event sourcing (sbtb, sbtb2015)
 
Developing event-driven microservices with event sourcing and CQRS (Shanghai)
Developing event-driven microservices with event sourcing and CQRS (Shanghai)Developing event-driven microservices with event sourcing and CQRS (Shanghai)
Developing event-driven microservices with event sourcing and CQRS (Shanghai)
 
Microservices + Events + Docker = A Perfect Trio (dockercon)
Microservices + Events + Docker = A Perfect Trio (dockercon)Microservices + Events + Docker = A Perfect Trio (dockercon)
Microservices + Events + Docker = A Perfect Trio (dockercon)
 
REST and Microservices
REST and MicroservicesREST and Microservices
REST and Microservices
 
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
 
Microservices: Decomposing Applications for Deployability and Scalability (ja...
Microservices: Decomposing Applications for Deployability and Scalability (ja...Microservices: Decomposing Applications for Deployability and Scalability (ja...
Microservices: Decomposing Applications for Deployability and Scalability (ja...
 
MicroService Architecture
MicroService ArchitectureMicroService Architecture
MicroService Architecture
 

Semelhante a “Insulin” for Scala’s Syntactic Diabetes

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Semelhante a “Insulin” for Scala’s Syntactic Diabetes (20)

Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Thea: Processing OWL Ontologies - An application of logic programming
Thea: Processing OWL Ontologies - An application of logic programmingThea: Processing OWL Ontologies - An application of logic programming
Thea: Processing OWL Ontologies - An application of logic programming
 
Processing OWL2 Ontologies using Thea: An application of Logic Programming
Processing OWL2 Ontologies using Thea: An application of Logic ProgrammingProcessing OWL2 Ontologies using Thea: An application of Logic Programming
Processing OWL2 Ontologies using Thea: An application of Logic Programming
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Let's refine your Scala Code
Let's refine your Scala CodeLet's refine your Scala Code
Let's refine your Scala Code
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
core java
 core java core java
core java
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

“Insulin” for Scala’s Syntactic Diabetes

  • 1. “Insulin” for Scala’s Syntactic Diabetes Tzach Zohar // Kenshoo // Scalapeño 2016
  • 2. OR: How to adopt Scala and survive source
  • 3.
  • 5. Who am I NOT Chuck Norris! Scala “Advanced Beginner” / “Competent” System Architect @ Kenshoo
  • 6. Who’s Kenshoo 10-year Tel-Aviv based startup Industry Leader in Digital Marketing Java + JavaScript shop http://kenshoo.com/
  • 7. Scala @ Kenshoo 5 services written in Scala More to come... Internal Scala course on the go
  • 9. trait GeneralizedCategory { type U <: Hom type =>:[A >: U#L <: U#H, B >: U#L <: U#H] = U#C[A, B] def id[A >: U#L <: U#H]: A =>: A def compose[A >: U#L <: U#H, B >: U#L <: U#H, C >: U#L <: U#H]( f: B =>: C, g: A =>: B): A =>: C def *[UY<:Hom](that : GeneralizedCategory {type U=UY}) = Category.ProductCategory[U,UY](this,that) } source
  • 11. source def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
  • 12. Now for some sane examples source
  • 13. val tuples = List((1, 374), (3, 42), (5, 693)) val ids = tuples.map(_._1) val ids = tuples.map(tuple => tuple._1) val ids = tuples.map { tuple => tuple._1 }
  • 14. val tuples = List((1, 374), (3, 42), (5, 693)) val ids = tuples.map(_._1) val ids = tuples.map(tuple => tuple._1) val ids = tuples.map { tuple => tuple._1 } val ids = tuples.map(t => t match { case (id, value)=> id }) val ids = tuples.map(_ match { case (id, value) => id }) val ids = tuples.map({ case (id, value) => id }) val ids = tuples.map { case (id, value) => id } val ids = tuples.map { case (id, _) => id }
  • 15. case class Profile() { … } case class ProfileId(id: Int) def loadProfile(profileId: ProfileId): Profile = ???
  • 16. case class Profile() { … } case class ProfileId(id: Int) def loadProfile(profileId: ProfileId): Profile = ??? loadProfile(ProfileId(3)) loadProfile(new ProfileId(3)) loadProfile(profileId = ProfileId(3)) loadProfile(profileId = new ProfileId(3))
  • 17. case class Profile() { … } case class ProfileId(id: Int) implicit def toId(i :Int): ProfileId = ProfileId(i) def loadProfile(profileId: ProfileId): Profile = ??? loadProfile(ProfileId(3)) loadProfile(new ProfileId(3)) loadProfile(profileId = ProfileId(3)) loadProfile(profileId = new ProfileId(3)) loadProfile(3) loadProfile(profileId = 3)
  • 18. def loadInt(): Int = { … } def f(value: () => Int) = { … } f(() => 2 + loadInt())
  • 19. def loadInt(): Int = { … } def f(value: () => Int) = { … } f(() => 2 + loadInt()) def f(value: => Int) = { … } f(2 + loadInt())
  • 21. Issues so far Too many ways to write the same thing Tradeoff between short and readable Advanced features getting in the way
  • 22. Insulin to the rescue
  • 24. Style Guides 1. The basic: Official Scala-Lang Style Guide 2. The conservative: Databricks' Scala Style Guide 3. The exhaustive: Twitter's Effective Scala 4. Your own!
  • 25. Style Guides implicit def toId(i :Int): ProfileId = ProfileId(i) loadProfile(ProfileId(3)) loadProfile(3) “Do not use implicits to do automatic conversions between similar datatypes”
  • 26. Style Guides “Avoid infix notation for methods that aren't symbolic methods” list map func string contains "foo" list.map(func) string.contains("foo") val x = y + 2
  • 27. Style Guides val ids = tuples.map(t => t match { case (id, value)=> id }) val ids = tuples.map(_ match { case (id, value) => id }) val ids = tuples.map { case (id, value) => id } val ids = tuples.map { case (id, _) => id } “Use pattern matching directly in function definitions whenever applicable”
  • 28. Style Guides def f(value: => Int) = ??? f(2 + 3) def f(value: () => Int) = ??? f(() => 2 + 3) “Avoid using call by name. Use () => T explicitly”
  • 29. @throws[IOException] def mightThrowException(): Int def neverThrowsException(): Option[Int] def neverThrowsException(): Try[Int] def neverThrowsException(): Either[Int, String] def neverThrowsException(): MyResult Style Guides “Scala provides an exception facility, but do not use it for commonplace errors”
  • 30. val ids = tuples.map(_._1) val ids = tuples.map(tuple => tuple._1) val ids = tuples.map { case (id, value) => id } val ids = tuples.map { case (id, _) => id } Style Guides “Avoid using tuple field names like _1, prefer pattern matching or a dedicated case class”
  • 32. Code Reviews Refer author to Style Guides Mix “Scala Levels” - juniors should review seniors’ code
  • 35. Code Reviews [Only] methods which act as accessors [...] should be declared without parentheses, except if they have side effects
  • 37. Style Checkers Automate some of the (simpler) rules 1. Scalastyle (SBT/Gradle/Maven/Eclipse/IntelliJ) 2. Scalafmt (SBT/Vim/CLI/IntelliJ) [NEW]
  • 38. ⌚ 18:45:25 ➜ sbt scalastyle [info] Loading project definition from /.../project [info] Set current project to myProject (in build file:/.../) [warn] MyJob.scala:31:6: parameter.number.message [error]MyService.scala:42:6: public.methods.have.type.message [info] Processed 42 file(s) [info] Found 1 errors [info] Found 2 warnings [info] Found 0 infos [info] Finished in 39 ms Style Checkers
  • 40. Scala Levels Application Programmer Library Designer A1: Beginner L1: Junior A2: Intermediate L2: Senior A3: Expert L3: Expert Defined by Martin Odersky in a 2011 post
  • 41. Scala Levels Application Includes A1: Beginner Basic syntax; Simple Closures; Collections; For-expressions; … A2: Intermediate Pattern matching; Trait composition; (Tail) Recursion; … A3: Expert Folds; Streams + other lazy data structures; Actors; …
  • 42. Scala Levels Library Includes L1: Junior Type parameters; Traits; Lazy vals; Currying; By-name parameters L2: Senior Variance; Existential types; Cake Pattern; Structural types; Extractors; … L3: Expert Early initializers; Abstract types; Implicit definitions; Higher-kinded types; …
  • 43. source def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
  • 46. 1. Intermediate Scala works (might be better than Expert Java!) 2. Style and Feature-set can be controlled 3. No Chuck-Norrisness Required source