Upload
huffpost-code
View
2.648
Download
1
Tags:
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
SCALA FOR PHP DEVELOPERSJOSEPH PRICE
● ‘scalable language’o scales from small to large problems
● object-functional
● runs on JVM
● performant
● concise o type inferenceo reduced repetition
Scala
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
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
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
Type safety
● more confident in changeso library / api updateso refactoring
● static analysis● find errors more quickly● avoid common errors● compiler can optimize typed code
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
Concurrency
● immutability enables thread safetyo concurrent access to shared mutable state
● Promises / Futures● actors● parallel collections
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
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
Pattern Matching
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
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
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
Collections
immutable / mutable● immutable preferred
Most commonly used are
Map, List, Seq
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
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
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)
DSLs - Slickslick.typesafe.com
‘Functional relational mapping’makes use of familiar collections apican drop down to raw SQL
DSLs - sbthttp://www.scala-sbt.org/
Actor Model
asynchronous message passing between lightweight processes
isolate mutable state
lifecycle● let it crash™● fault tolerance● remoting
Play
● MVC web framework● Asynchronous● Non-blocking● Built on Akka, Netty● Highly customizable● Industry support
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
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
Thanks!