SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
Introduction to Scala
by Michel Perez
www.mrkaspa.com
Good Parts
2
JVM & JAVA INTEROPERABILITY STATICALLY TYPED
TYPE INFERENCE REPL
EXPLICIT MUTABILITY NO SEMICOLON
EVERYTHING IS AN OBJECT MIXINS
Bad Parts
3
IDE JARS & MAVEN
LEARNING GURVE COMPILE TIME
Object Oriented Programming
CLASSES OBJECTS
VISIBILITY INTERFACES
ABSTRACT CLASS INHERITANCE
Scala Variables & Values
5
val labels = Set(“")
val labels = Set[String](“”)
var labels = Set[String](“”)
Mutables
Inmutables
Type Inference
Visibility
6
Public by default
Instance private to the current instanceval Num = 1
private[this] val Num = 1
private val Num = 1
private[package] val Num = 1
protected val Num = 1
Instance private to the class
Instance private to a custom package
Instance protected to its children
Classes
7
Case class -> get, set, constructor auto
Traits -> Interfaces + Mixins
Generic clases/traits
Singleton Object
case class SocialNetwork(id: String, name: String)
trait LinkedList[+A] {

def isEmpty: Boolean



def head: A



def tail: LinkedList[A]



def at(index: Int): A



def prepend[B >: A](elem: B): LinkedList[B] =
new Cons(elem, this)
}

object Nil extends LinkedList[Nothing] {
class Cons[A](val head: A, val tail: LinkedList[A]) extends LinkedList[A] {
Mixins
8
Typesafe
Multiple inheritance
trait NeoTest

extends FunSpec

with MustMatchers

with BeforeAndAfterAll

with BeforeAndAfterEach {



}

trait HelperTest {

this: NeoTest =>
}
class NodeSpec extends NeoTest with HelperTest {
}
Used for composition
Abstract class
9
Java compatibilityabstract class Rel[A, B] {

val from: A

val to: B

}
case class MyRel(from: MyUser, to: MyUser,
enabled: Boolean) extends Rel[MyUser, MyUser]
Can not be instantiated
Can have a constructor
Relation is-a
Functional Programming
FUNCTIONS AS FIRST CITIZENS IMMUTABILITY
CURRYING CLOSURES
LAZY EVALUATION PATTERN MATCHING
TYPE CLASS ALGEBRAIC DATATYPES
Scala Functions
11
Every function must have a return type
Functions as parameters
You can return functions
Vector.fill(queens.length)("* “)
.updated(col, "X ").mkString
def lambda = (x: Int) => x + 1
val multiplier = (i:Int) => i * 10
def sumComp(a: Int): (Int) => Int = {

def sum(b: Int) = a + b

}
val fun = sumComp(5)

fun(1)
def sumComp(a: Int)(b: Int): Int = {

a + b

}
Currying
Pattern Matching
12
Like a super switchval secondElement = List(1,2,3) match {

case x :: y :: xs => y

case _ => 0

}
val foodItem = "porridge"



def goldilocks(expr: Any) = expr match {

case (`foodItem`, _) => "eating"

case ("chair", "Mama") => "sitting"

case ("bed", "Baby") => "sleeping"

case _ => "what?"

}



goldilocks(("porridge", "Papa"))
Compare & extract
Implicits
13
Inject parameters to a method
Automatic conversation
implicit def implChange(str:String):Int =
new Integer(str)



def sum(a:Int, b:Int):Int = a +b



sum("1", 2)
def save[T](t: T)(implicit connection: Neo4jREST,
ec: ExecutionContext):
Monads
14
map, flatMap, filter
for comprehension
def readAsync(): Future[Option[List[String]]] =

Future { readFile() }


def readFile(): Option[List[String]] =

Try { Source.fromURL("/tmp/file.txt").getLines().toList

} toOption


val futSize: Future[Int] =

for {

result <- readAsync()

list <- result

} yield list.size


val futSizeMap: Future[Option[Int]] =

readAsync().map { result: Option[List[String]] =>

result.map((list: List[String]) => list.size)

}
Future, Option, Try, Either
Type Class
Pattern
15
AKA context bound
implicit val myUserMapper = Mapper.build[MyUser]
abstract class NeoNode[T: Mapper] extends Labelable {

val MapperT = implicitly[Mapper[T]]
def save(t: T)(implicit connection: Neo4jREST, ec: ExecutionContext):
Future[Boolean] = Future {}
object ToOps{

implicit def operations(t: T) = NeoNodeOperations(t)

}
case class NeoNodeOperations(t: T) {

def save()(implicit connection: Neo4jREST, ec: ExecutionContext) =
NeoNode.this.save(t)
}
}
case class MyUser(id: String, name: String, age: Int)
implicit val userNode = NeoNode("user", (user: MyUser) => user.id)
import graph.model.orm.UserNodes.userNode.ToOps._
val node1 = MyUser("1", "Michel Perez", 27)
node1.save()
Mix traits - abstract class
& implicit
Good Ecosystem
AKKA PLAY FRAMEWORK
SPARK SBT
SCALOID SCALAJS
ORMS TYPELEVEL
SCALAJSFINAGLE
Actors
17
Lightweight threads
Event oriented
class BloodRequester extends Actor {



implicit val executor = context.dispatcher



override def receive: Receive = {

case BloodRequest(request) =>

DonorDAO.findNear(request).map { donors =>

donors.foreach { donor =>

facebookNotifier ! FacebookNotify(donor, request)

}

}

}



}
Restart in failures
Supervision
ScalaTest
18
Test Unit
trait NeoTest

extends FunSpec

with MustMatchers

with BeforeAndAfterAll

with BeforeAndAfterEach {
override def beforeEach(): Unit = {

NeoDBCleaner.cleanDB()

}
describe("UserDAOs") {

it("creates an user an checks the default group") {

withUser { (user, saved) =>

saved must be(true)

val query = s"""match (a:user {id: "${user.id.getOrElse("")}"})-[c:has_group]-
>(b:group) return a, b, c"""

val result = Await.result(NeoQuery.executeQuery[UserLogin, Group, HasGroupLogin]
(query), 2 seconds)

result.length must be(1)

}

}
}

Multiple Paradigms
TDD
BDD
ScalaZ
19
Inspired in Haskell
case class Box[A](itemType: A)
implicit val machFunctor = new Functor[Box] {

override def map[A, B](fa: Box[A])(f: (A) => B): Box[B] = {

val b = f(fa.itemType)

Box(b)

}

}
import machFunctor.functorSyntax._
val boxInt = Box(1)
val boxString = boxInt map { x => s"$x..." }
More functional
Scala wants U ;)
20
https://www.coursera.org/course/progfun
http://scala-exercises.47deg.com/koans

Contenu connexe

Tendances

Tendances (14)

Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
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
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 

En vedette (13)

Para Deleitar La Vista Y El Oido
Para Deleitar La Vista Y El OidoPara Deleitar La Vista Y El Oido
Para Deleitar La Vista Y El Oido
 
Fotografo Aleman fotos
Fotografo Aleman fotosFotografo Aleman fotos
Fotografo Aleman fotos
 
Los Resistentes 2
Los Resistentes 2Los Resistentes 2
Los Resistentes 2
 
Bazar do alemão!
Bazar do alemão!Bazar do alemão!
Bazar do alemão!
 
4. anexo iv regulamento da concessão
4. anexo iv   regulamento da concessão4. anexo iv   regulamento da concessão
4. anexo iv regulamento da concessão
 
Informativo insp 33
Informativo insp   33Informativo insp   33
Informativo insp 33
 
Proyecto Vic Dream Disco
Proyecto Vic Dream DiscoProyecto Vic Dream Disco
Proyecto Vic Dream Disco
 
España física
España  físicaEspaña  física
España física
 
why men die young
why men die youngwhy men die young
why men die young
 
Yovana Chango
Yovana ChangoYovana Chango
Yovana Chango
 
Master Postgrad Study Description - Sergio Gallego Schmid
Master Postgrad Study Description  - Sergio Gallego SchmidMaster Postgrad Study Description  - Sergio Gallego Schmid
Master Postgrad Study Description - Sergio Gallego Schmid
 
Cultura Italia
Cultura ItaliaCultura Italia
Cultura Italia
 
Horoscope
HoroscopeHoroscope
Horoscope
 

Similaire à Introduction to scala

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Similaire à Introduction to scala (20)

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?
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
Scala
ScalaScala
Scala
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Introduction to scala

  • 1. Introduction to Scala by Michel Perez www.mrkaspa.com
  • 2. Good Parts 2 JVM & JAVA INTEROPERABILITY STATICALLY TYPED TYPE INFERENCE REPL EXPLICIT MUTABILITY NO SEMICOLON EVERYTHING IS AN OBJECT MIXINS
  • 3. Bad Parts 3 IDE JARS & MAVEN LEARNING GURVE COMPILE TIME
  • 4. Object Oriented Programming CLASSES OBJECTS VISIBILITY INTERFACES ABSTRACT CLASS INHERITANCE
  • 5. Scala Variables & Values 5 val labels = Set(“") val labels = Set[String](“”) var labels = Set[String](“”) Mutables Inmutables Type Inference
  • 6. Visibility 6 Public by default Instance private to the current instanceval Num = 1 private[this] val Num = 1 private val Num = 1 private[package] val Num = 1 protected val Num = 1 Instance private to the class Instance private to a custom package Instance protected to its children
  • 7. Classes 7 Case class -> get, set, constructor auto Traits -> Interfaces + Mixins Generic clases/traits Singleton Object case class SocialNetwork(id: String, name: String) trait LinkedList[+A] {
 def isEmpty: Boolean
 
 def head: A
 
 def tail: LinkedList[A]
 
 def at(index: Int): A
 
 def prepend[B >: A](elem: B): LinkedList[B] = new Cons(elem, this) }
 object Nil extends LinkedList[Nothing] { class Cons[A](val head: A, val tail: LinkedList[A]) extends LinkedList[A] {
  • 8. Mixins 8 Typesafe Multiple inheritance trait NeoTest
 extends FunSpec
 with MustMatchers
 with BeforeAndAfterAll
 with BeforeAndAfterEach {
 
 }
 trait HelperTest {
 this: NeoTest => } class NodeSpec extends NeoTest with HelperTest { } Used for composition
  • 9. Abstract class 9 Java compatibilityabstract class Rel[A, B] {
 val from: A
 val to: B
 } case class MyRel(from: MyUser, to: MyUser, enabled: Boolean) extends Rel[MyUser, MyUser] Can not be instantiated Can have a constructor Relation is-a
  • 10. Functional Programming FUNCTIONS AS FIRST CITIZENS IMMUTABILITY CURRYING CLOSURES LAZY EVALUATION PATTERN MATCHING TYPE CLASS ALGEBRAIC DATATYPES
  • 11. Scala Functions 11 Every function must have a return type Functions as parameters You can return functions Vector.fill(queens.length)("* “) .updated(col, "X ").mkString def lambda = (x: Int) => x + 1 val multiplier = (i:Int) => i * 10 def sumComp(a: Int): (Int) => Int = {
 def sum(b: Int) = a + b
 } val fun = sumComp(5)
 fun(1) def sumComp(a: Int)(b: Int): Int = {
 a + b
 } Currying
  • 12. Pattern Matching 12 Like a super switchval secondElement = List(1,2,3) match {
 case x :: y :: xs => y
 case _ => 0
 } val foodItem = "porridge"
 
 def goldilocks(expr: Any) = expr match {
 case (`foodItem`, _) => "eating"
 case ("chair", "Mama") => "sitting"
 case ("bed", "Baby") => "sleeping"
 case _ => "what?"
 }
 
 goldilocks(("porridge", "Papa")) Compare & extract
  • 13. Implicits 13 Inject parameters to a method Automatic conversation implicit def implChange(str:String):Int = new Integer(str)
 
 def sum(a:Int, b:Int):Int = a +b
 
 sum("1", 2) def save[T](t: T)(implicit connection: Neo4jREST, ec: ExecutionContext):
  • 14. Monads 14 map, flatMap, filter for comprehension def readAsync(): Future[Option[List[String]]] =
 Future { readFile() } 
 def readFile(): Option[List[String]] =
 Try { Source.fromURL("/tmp/file.txt").getLines().toList
 } toOption 
 val futSize: Future[Int] =
 for {
 result <- readAsync()
 list <- result
 } yield list.size 
 val futSizeMap: Future[Option[Int]] =
 readAsync().map { result: Option[List[String]] =>
 result.map((list: List[String]) => list.size)
 } Future, Option, Try, Either
  • 15. Type Class Pattern 15 AKA context bound implicit val myUserMapper = Mapper.build[MyUser] abstract class NeoNode[T: Mapper] extends Labelable {
 val MapperT = implicitly[Mapper[T]] def save(t: T)(implicit connection: Neo4jREST, ec: ExecutionContext): Future[Boolean] = Future {} object ToOps{
 implicit def operations(t: T) = NeoNodeOperations(t)
 } case class NeoNodeOperations(t: T) {
 def save()(implicit connection: Neo4jREST, ec: ExecutionContext) = NeoNode.this.save(t) } } case class MyUser(id: String, name: String, age: Int) implicit val userNode = NeoNode("user", (user: MyUser) => user.id) import graph.model.orm.UserNodes.userNode.ToOps._ val node1 = MyUser("1", "Michel Perez", 27) node1.save() Mix traits - abstract class & implicit
  • 16. Good Ecosystem AKKA PLAY FRAMEWORK SPARK SBT SCALOID SCALAJS ORMS TYPELEVEL SCALAJSFINAGLE
  • 17. Actors 17 Lightweight threads Event oriented class BloodRequester extends Actor {
 
 implicit val executor = context.dispatcher
 
 override def receive: Receive = {
 case BloodRequest(request) =>
 DonorDAO.findNear(request).map { donors =>
 donors.foreach { donor =>
 facebookNotifier ! FacebookNotify(donor, request)
 }
 }
 }
 
 } Restart in failures Supervision
  • 18. ScalaTest 18 Test Unit trait NeoTest
 extends FunSpec
 with MustMatchers
 with BeforeAndAfterAll
 with BeforeAndAfterEach { override def beforeEach(): Unit = {
 NeoDBCleaner.cleanDB()
 } describe("UserDAOs") {
 it("creates an user an checks the default group") {
 withUser { (user, saved) =>
 saved must be(true)
 val query = s"""match (a:user {id: "${user.id.getOrElse("")}"})-[c:has_group]- >(b:group) return a, b, c"""
 val result = Await.result(NeoQuery.executeQuery[UserLogin, Group, HasGroupLogin] (query), 2 seconds)
 result.length must be(1)
 }
 } }
 Multiple Paradigms TDD BDD
  • 19. ScalaZ 19 Inspired in Haskell case class Box[A](itemType: A) implicit val machFunctor = new Functor[Box] {
 override def map[A, B](fa: Box[A])(f: (A) => B): Box[B] = {
 val b = f(fa.itemType)
 Box(b)
 }
 } import machFunctor.functorSyntax._ val boxInt = Box(1) val boxString = boxInt map { x => s"$x..." } More functional
  • 20. Scala wants U ;) 20 https://www.coursera.org/course/progfun http://scala-exercises.47deg.com/koans