34
SCALA FOR PHP DEVELOPERS JOSEPH PRICE

An Intro to Scala for PHP Developers

Embed Size (px)

DESCRIPTION

Joseph Price, a software engineer at The Huffington Post gave a talk about the basics of Scala. These slides are a great resource for anyone who's interested in learning more about Scala. PHP knowledge is not required.

Citation preview

Page 1: An Intro to Scala for PHP Developers

SCALA FOR PHP DEVELOPERSJOSEPH PRICE

Page 2: An Intro to Scala for PHP Developers

● ‘scalable language’o scales from small to large problems

● object-functional

● runs on JVM

● performant

● concise o type inferenceo reduced repetition

Scala

Page 3: An Intro to Scala for PHP Developers

Object Orientation

● Everything’s an object o 1.toDouble

● Supports typical OO functionality - classes, methods, interfaces, inheritance, polymorphism, encapsulation, access modifiers

● Traitso interface with implementationo allows multiple inheritance o avoids ‘diamond problem’ through a technique called

linearization

Page 4: An Intro to Scala for PHP Developers
Page 5: An Intro to Scala for PHP Developers

Functional programming● ‘first-class’ functions

o anonymouso function valueso passed to and returned

from functionso higher order functions

map, filter, flatMap

● immutable data structures

● isolation of state, side effects

Page 6: An Intro to Scala for PHP Developers

Immutability

● most methods return a new objecto immutable data structures

● val / var● input params cannot change● iteration - contrast to imperative style

o prefer map / fold over stateful looping

Page 7: An Intro to Scala for PHP Developers

Type safety

● more confident in changeso library / api updateso refactoring

● static analysis● find errors more quickly● avoid common errors● compiler can optimize typed code

Page 8: An Intro to Scala for PHP Developers

Type inference

Typing required for● Method signatures● Class members● Recursive methods

Optional elsewhere

Should be annotated on public methods● Avoid returning too generic/specific type● Api stability

Page 9: An Intro to Scala for PHP Developers

Concurrency

● immutability enables thread safetyo concurrent access to shared mutable state

● Promises / Futures● actors● parallel collections

Page 10: An Intro to Scala for PHP Developers

val - immutable and immediately evaluated

var - mutable and immediately evaluated

def ● calculates value on each access (same as a method)● uniform access principle

lazy val● calculated on first access● avoid recalculating

Variables vs Values

Page 11: An Intro to Scala for PHP Developers
Page 12: An Intro to Scala for PHP Developers
Page 13: An Intro to Scala for PHP Developers

Classes, Case classes, Objectsclasses

● body is the constructor

● getters / setters generated

● public by defaulto private, protected, restricted private[controllers]

case classes

● pattern match

● simplify common operations when working with classes as data

● generated apply, toString, equals, copy methods

singleton objects

● common pattern that can be implemented in many (mostly incorrect) ways

● companion objects - shares name and file, holds ‘static’ methods and has privileged access

Page 14: An Intro to Scala for PHP Developers
Page 15: An Intro to Scala for PHP Developers

Pattern Matching

Page 16: An Intro to Scala for PHP Developers

Option

represents presence/absence of a result

algebraic data structure● can be either Some or None

null handling● empty(), is_null(), isset()● if x != null ● callers are forced to handle absence

Page 17: An Intro to Scala for PHP Developers
Page 18: An Intro to Scala for PHP Developers

Try

● represents success or failure of an expression● Success / Failure● handle result by calling map, handle failure by

calling recover● moves try/catch control structure into type

system

Page 19: An Intro to Scala for PHP Developers

Future

● simplifies asynchronous computation● similar interface to Try● read-only view of a promise’s result● Promises produce values asynchronously, future

allows binding of callbacks● similar to jQuery Deferred / Angular promise

Page 20: An Intro to Scala for PHP Developers
Page 21: An Intro to Scala for PHP Developers
Page 22: An Intro to Scala for PHP Developers

Collections

immutable / mutable● immutable preferred

Most commonly used are

Map, List, Seq

Page 23: An Intro to Scala for PHP Developers
Page 24: An Intro to Scala for PHP Developers

Magic / dragons● can be abused, affect compile times● simplify apis by reducing overhead

implicit parameters● avoid passing parameters repetitively

extension methods● via implicit classes / conversions● ad-hoc polymorphism

Implicit scope

Page 25: An Intro to Scala for PHP Developers

DSLs

domain specific language

internal ● Slick, Scalikejdbc, sbt ● make use of implicits, operator

overloading, macros, advanced type system features

external● library support via parser

combinators

Page 26: An Intro to Scala for PHP Developers

DSLs - ScalikeJDBC

val programmers: List[Long] = DB readOnly { implicit session =>

withSQL {

select

.from(Programmer as p)

.leftJoin(Company as c).on(p.companyId, c.id)

.where.eq(p.isDeleted, false)

.orderBy(p.createdAt)

.limit(10)

.offset(0)

}.map(Programmer(p, c)).list.apply()}http://scalikejdbc.org/

Typesafe api that compiles to SQL

Makes use of advanced features like Macros and Type Dynamic (like php’s ‘magic methods’ or Ruby’s method_missing)

Page 27: An Intro to Scala for PHP Developers

DSLs - Slickslick.typesafe.com

‘Functional relational mapping’makes use of familiar collections apican drop down to raw SQL

Page 28: An Intro to Scala for PHP Developers

DSLs - sbthttp://www.scala-sbt.org/

Page 29: An Intro to Scala for PHP Developers

Actor Model

asynchronous message passing between lightweight processes

isolate mutable state

lifecycle● let it crash™● fault tolerance● remoting

Page 30: An Intro to Scala for PHP Developers

Play

● MVC web framework● Asynchronous● Non-blocking● Built on Akka, Netty● Highly customizable● Industry support

Page 31: An Intro to Scala for PHP Developers

Environment

JVM● garbage collection, JIT compilation● reuse existing libraries● Java interop - call Java code from Scala and vice versa● tooling, instrumentation

SBT

IDEs● IntelliJ, Eclipse

o weak support initially, but steadily improving

Page 32: An Intro to Scala for PHP Developers
Page 33: An Intro to Scala for PHP Developers

Resourceshttp://blog.jetbrains.com/scala/2012/12/04/scala-worksheet/ - for IntelliJ

https://github.com/scala-ide/scala-worksheet/wiki/Getting-Started - for Eclipse

http://www.scala-sbt.org/ - scala’s build tool

http://mvnrepository.com/ - find dependencies

http://slick.typesafe.com/ - db access using collections-like interfacehttps://github.com/slick/slick-examples/blob/master/src/main/scala/com/typesafe/slick/examples/lifted/FirstExample.scala- example slick code

http://scalikejdbc.org/ - sql dsl

http://akka.io/ - actors, software transactional memory

http://letitcrash.com/ - akka blog

https://typesafe.com/activator/templates - many example projects to get you started

http://docs.scala-lang.org/overviews/collections/performance-characteristics.html - collections complexityhttp://docs.scala-lang.org/resources/images/collections.immutable.png - immutable collections class hierarchyhttp://docs.scala-lang.org/resources/images/collections.mutable.png - mutable collections class hierarchy

Page 34: An Intro to Scala for PHP Developers

Thanks!